无法从更新片段UI的onActivityResult [英] Not able to update Fragment UI from onActivityResult

查看:347
本文介绍了无法从更新片段UI的onActivityResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个应用程序在具有延伸FragmentActivity一类。
在onResume()方法,我打电话一类而我送这个fragmentactivity参考,并在该类我与另一片段取代它。

在该片段,我动态添加的布局,但是当我点击我打电话startActivityForResult()反过来在收到的onActivityResult结果的按钮()中,我试图更新的EditText的文字,但它没有发生。当我点击后退按钮我能看到的文字上的EditText改变。谁能帮我整理出这个问题。 I'will在这里发表我的整个源$ C ​​$ C。结果

MainActivity.java

 公共类MainActivity扩展FragmentActivity {// FragmentActivity语境;
上下文语境;
FragmentManager调频;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);    上下文= MainActivity.this;   / * FM = getSupportFragmentManager();
    FragmentManager FM = getSupportFragmentManager();
    片段multiFormScreenFragment = MultiFormScreenFragment.newInstance(1);
    fm.beginTransaction()
    .replace(R.id.fragment_container,multiFormScreenFragment)
    。承诺();
* /
    }
@覆盖
保护无效onResume(){
    // TODO自动生成方法存根
    super.onResume();
     新LoadScreenHelper((FragmentActivity)上下文,R.id.fragment_container).loadTargetScreen(,1,,1,假,,,);
}      }

LoadScreenHelper.java

 包com.cognizant.aim.LoadScreen; 进口com.android.testfragmentactivityresult.MultiFormScreenFragment;    公共类LoadScreenHelper {公共FragmentActivity语境;
//公共上下文的背景下;
INT mContainerId = -1;
公共LoadScreenHelper(FragmentActivity C中,int containerId){    上下文= C;
    mContainerId = containerId;
}
公共无效loadTargetScreen(字符串screenType,INT nav_id,字符串USID,INT screenorder,布尔isMain,字符串filterColumnName,字符串filterColumnVal,字符串uiHeadingTitle){// uiHeadingTitle    的System.out.println(ScreenType ::::+ screenType +nav_id+ nav_id +:::+screenorder ::::+ screenorder);    束束=新包();
    bundle.putInt(screenOrder,1);
    bundle.putString(UNIQUEID,1);
    bundle.putString(称号,表);
    // bundle.putString(tableName值,dataSourceTableName);
    // bundle.putString(ROWID,clicked_list_row_Id);    FragmentManager FM = context.getSupportFragmentManager();
    片段multiFormScreenFragment = MultiFormScreenFragment.newInstance(1 / * screenId * /);
    multiFormScreenFragment.setArguments(包);
    如果(isMain){
        fm.beginTransaction()
        .replace(mContainerId,multiFormScreenFragment)
        。承诺();
    }
    其他{
        fm.beginTransaction()
        .replace(mContainerId,multiFormScreenFragment)
        .addToBackStack(空)
        。承诺();    }}       }

MultiFormScreenFragment.java

 公共类MultiFormScreenFragment扩展片段{
   查看视图。
INT mContainerId = -1;
私有静态最后弦乐TAG =MultiFormScreenFragment;
的LinearLayout llayout;
公共静态的newInstance MultiFormScreenFragment(INT PARENTID){
    MultiFormScreenFragment F =新MultiFormScreenFragment();
    束B =新包();
    b.putInt(LIST_ID,PARENTID);
    f.setArguments(二);
    返回F;
}@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);
}
@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
        捆绑savedInstanceState){
    // TODO自动生成方法存根
    mContainerId = container.getId();
    鉴于= inflater.inflate(R.layout.activity_main,集装箱,FALSE);
    llayout =(的LinearLayout)view.findViewById(R.id.llayout);
    generateUILayout();    返回视图。
}私人无效generateUILayout(){
    // TODO自动生成方法存根
    LinearLayout.LayoutParams PARAMS =新LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    按钮newBtn =新按钮(getActivity());
    newBtn.setLayoutParams(PARAMS);
    newBtn.setId(1);
    newBtn.setText(演示);
    llayout.addView(newBtn);    的EditText newEText =新的EditText(getActivity());
    newBtn.setLayoutParams(PARAMS);
    newEText.setId(2);
    newEText.setText(演示);    llayout.addView(newEText);    newBtn.setOnClickListener(新OnClickListener(){        @覆盖
        公共无效的onClick(视图v){
            // TODO自动生成方法存根
            意向意图=新意图(getActivity(),SecondActivity.class);
            intent.putExtra(sampleData在,这是示例数据);
            startActivityForResult(意向,1);        }
    });
}
@覆盖
公共无效的onActivityResult(INT申请code,INT结果code,意图数据){
    // TODO自动生成方法存根
    super.onActivityResult(要求code,结果code,数据);
    如果(结果code == getActivity()RESULT_OK和放大器;&安培;请求code == 1){
        弦乐味精= data.getStringExtra(returnedData);
        的EditText ETEXT =(的EditText)getActivity()findViewById(2)。
        eText.setText(MSG);
    }
}      }
  SecondActivity.java
  ===================    包com.android.testfragmentactivityresult;     进口android.app.Activity;
       进口android.content.Intent;
    进口android.os.Bundle;
        公共类SecondActivity延伸活动{ @覆盖
保护无效的onCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);
      意向意图= getIntent();
      弦乐味精= intent.getStringExtra(的sampleData);
      味精+ =,在添加三;
      intent.putExtra(returnedData,味精);
      的setResult(RESULT_OK,意向);
      完();
}
     }
 activity_main.xml中
 ==================     < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
的xmlns:工具=htt​​p://schemas.android.com/tool​​s
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:方向=垂直
机器人:ID =@ + ID / llayout>    < / LinearLayout中>
       main.xml中
       ========
        < XML版本=1.0编码=UTF-8&GT?;
      < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
         机器人:方向=垂直>        <的FrameLayout
           机器人:ID =@ + ID / fragment_container
          机器人:layout_width =match_parent
           机器人:layout_height =match_parent
         机器人:layout_weight =1/>       < / LinearLayout中>
        AndroidManifest.xml中
        ===================
          <清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
          包=com.android.testfragmentactivityresult
          安卓版code =1
       机器人:=的versionName1.0>       <用途-SDK
    安卓的minSdkVersion =8
    机器人:targetSdkVersion =15/>    <应用
    机器人:图标=@绘制/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme>
    <活动
        机器人:名字=。MainActivity
        机器人:标签=@字符串/ title_activity_main>
        &所述;意图滤光器>
            <作用机器人:名字=android.intent.action.MAIN/>            <类机器人:名字=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;    <活动
        机器人:名字=.SecondActivity
        >< /活性GT;
     < /用途>     < /清单>


解决方案

  

...但是当我点击我打电话startActivityForResult按钮()
  这反过来又接收的onActivityResult(),其中我结果
  尝试更新的EditText的文本,但它没有发生。什么时候
  我点击后退按钮,我能够看到的EditText文字修改


我想这是因为在<$ C $的 onResume 方法使用 LoadScreenHelper 的发生C> FragmentActivity 。请记住, onResume 总是会活动时谈到foregound叫,这也将发生在活动后开始与 startActivityForResult 将返回。现在,通过调用的 loadTargetScreen()方法,你永远添加一个新的 LoadScreenHelper MultiFormScreenFragment 初始 FragmentActivity 。当你从孩子回来活动 onResume 方法将被再次调用一个新的 MultiFormScreenFragment 将创建最有可能覆盖最初添加片段。如果您单击后退按钮这顶片段会从屏幕上留下最初加入的片段被删除。

由于我不知道你想与 LoadScreenHelper 班结束时,我会建议要么做招行是什么:

 新LoadScreenHelper((FragmentActivity)的背景下,R.id.fragment_container).loadTargetScreen(,1,1,假的,,,) ;

的onCreate 方法,因此它只执行一次,或插入在 loadTargetScreen 的方法进行检查,找出如果一个实例 MultiFormScreenFragment 是不是已经在布局(使用 FragmentManager 找到片段)。如果是已经在布局那么就没有别的添加片段的新实例。

I'm working on an app in which has a class that extends FragmentActivity. In the onResume() method I was calling a class for which I am sending the reference of this fragmentactivity and in that class I'm replacing it with another fragment.

In that Fragment I'm dynamically adding the layout , but when I click on the button I'm Calling startActivityForResult() which in turn receives results in OnActivityResult() in which I'm trying to update the text of EditText , but it is not happening. When I clicked back button I'm able to see the text on EditText changed . Can anyone help me in sorting out this issue. I'will post my entire source code here .

MainActivity.java:

public class MainActivity extends FragmentActivity {

//FragmentActivity context;
Context context;
FragmentManager fm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    context = MainActivity.this;

   /* fm = getSupportFragmentManager();
    FragmentManager fm = getSupportFragmentManager();
    Fragment multiFormScreenFragment = MultiFormScreenFragment.newInstance(1 );
    fm.beginTransaction()
    .replace(R.id.fragment_container, multiFormScreenFragment)
    .commit();
*/
    }


@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
     new LoadScreenHelper((FragmentActivity)context,               R.id.fragment_container).loadTargetScreen("", 1,"",1,false,"","","");
}



      }

LoadScreenHelper.java:

 package com.cognizant.aim.LoadScreen;

 import com.android.testfragmentactivityresult.MultiFormScreenFragment;

    public class LoadScreenHelper {

public FragmentActivity context;
//public Context context;
int mContainerId=-1;
public LoadScreenHelper(FragmentActivity c,int containerId){

    context =  c;
    mContainerId  = containerId ;
}




public void loadTargetScreen(String screenType,int nav_id,String usid,int screenorder, boolean isMain,String filterColumnName,String filterColumnVal,String uiHeadingTitle){//uiHeadingTitle

    System.out.println("ScreenType::::"+screenType+"nav_id"+nav_id+":::"+"screenorder::::"+screenorder);



    Bundle bundle = new Bundle();
    bundle.putInt("screenOrder", 1);
    bundle.putString("uniqueid", "1");
    bundle.putString("title", "Form");
    //  bundle.putString("tableName", dataSourceTableName);   
    // bundle.putString("rowId",  clicked_list_row_Id);

    FragmentManager fm = context.getSupportFragmentManager();
    Fragment multiFormScreenFragment = MultiFormScreenFragment.newInstance(1 /*screenId*/);
    multiFormScreenFragment.setArguments(bundle);
    if(isMain){
        fm.beginTransaction()
        .replace(mContainerId, multiFormScreenFragment)
        .commit();
    }
    else{
        fm.beginTransaction()
        .replace(mContainerId, multiFormScreenFragment)
        .addToBackStack("null")
        .commit();

    }

}

       }

MultiFormScreenFragment.java:

      public class MultiFormScreenFragment  extends Fragment {
   View view;
int mContainerId = -1;
private static final String TAG = "MultiFormScreenFragment";
LinearLayout llayout;
public   static  MultiFormScreenFragment  newInstance(int parentid) {
    MultiFormScreenFragment f = new MultiFormScreenFragment();
    Bundle b = new Bundle();
    b.putInt("list_id", parentid);
    f.setArguments(b);
    return f;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);


}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    mContainerId =   container.getId();  
    view = inflater.inflate(R.layout.activity_main, container, false);
    llayout = (LinearLayout)view.findViewById(R.id.llayout);
    generateUILayout();

    return view;
}

private void generateUILayout() {
    // TODO Auto-generated method stub
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    Button newBtn = new Button(getActivity());
    newBtn.setLayoutParams(params);
    newBtn.setId(1);
    newBtn.setText("Demo");
    llayout.addView(newBtn);

    EditText newEText = new EditText(getActivity());
    newBtn.setLayoutParams(params);
    newEText.setId(2);
    newEText.setText("Demo");

    llayout.addView(newEText);

    newBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getActivity(), SecondActivity.class);
            intent.putExtra("sampleData", "This is Sample Data");
            startActivityForResult(intent, 1);

        }
    });


}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode==getActivity().RESULT_OK && requestCode==1){
        String msg = data.getStringExtra("returnedData");
        EditText eText = (EditText)getActivity().findViewById(2);
        eText.setText(msg);
    }
}



      }


  SecondActivity.java
  ===================

    package com.android.testfragmentactivityresult;

     import android.app.Activity;
       import android.content.Intent;
    import android.os.Bundle;


        public class SecondActivity extends Activity {

 @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
      Intent intent= getIntent();
      String msg = intent.getStringExtra("sampleData");
      msg += ", Added at Third";
      intent.putExtra("returnedData", msg);
      setResult(RESULT_OK, intent);
      finish();
}
     }


 activity_main.xml
 ==================

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/llayout">

    </LinearLayout>


       main.xml
       ========
        <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         android:orientation="vertical" >

        <FrameLayout
           android:id="@+id/fragment_container"
          android:layout_width="match_parent"
           android:layout_height="match_parent"
         android:layout_weight="1" />

       </LinearLayout> 


        AndroidManifest.xml
        ===================
          <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.android.testfragmentactivityresult"
          android:versionCode="1"
       android:versionName="1.0" >

       <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

    <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name = ".SecondActivity"
        ></activity>
     </application>

     </manifest>

解决方案

...but when I click on the button I'm Calling startActivityForResult() which in turn receives results in OnActivityResult() in which I'm trying to update the text of EditText , but it is not happening. When I clicked back button I'm able to see the text on EditText changed

I think this is happening because of the use of LoadScreenHelper in the onResume method of the FragmentActivity. Keep in mind that onResume will always be called when the activity comes to the foregound, this will also happen after the Activity started with startActivityForResult will return. Now by calling LoadScreenHelper's loadTargetScreen() method, you'll always add a new MultiFormScreenFragment to the initial FragmentActivity. When you come back from the child Activity the onResume method will be called again and a new MultiFormScreenFragment will be created most likely covering the initially added fragment. If you click the back button this top fragment will be removed from the screen leaving the initially added fragment.

As I don't know what you're trying to do in the end with the LoadScreenHelper class I would suggest to either move the line:

new LoadScreenHelper((FragmentActivity)context, R.id.fragment_container).loadTargetScreen("", 1,"",1,false,"","","");

in the onCreate method so it's executed only once, or insert a check in the loadTargetScreen method to find out if an instance of the MultiFormScreenFragment isn't already in the layout(use the FragmentManager to find the fragment). If it is already in the layout then do nothing else add a new instance of the fragment.

这篇关于无法从更新片段UI的onActivityResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆