无法从onActivityResult更新Fragment UI

时间:2012-12-18 19:19:06

标签: android android-layout android-fragments android-fragmentactivity

我正在开发一个应用程序,其中有一个扩展FragmentActivity的类。 在onResume()方法中,我调用了一个类,我发送了这个片段活动的引用,在那个类中,我用另一个片段替换它。

在那个片段中,我正在动态添加布局,但是当我点击按钮时,我正在调用startActivityForResult(),而后者又在OnActivityResult()中接收结果,其中我正在尝试更新EditText的文本,但它没有发生。当我单击后退按钮时,我能够看到EditText上的文本发生了变化。任何人都可以帮我解决这个问题。我会在这里发布我的完整源代码。

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>

1 个答案:

答案 0 :(得分:2)

  

...但是当我点击按钮时我正在调用startActivityForResult()   它反过来接收我在的OnActivityResult()中的结果   试图更新EditText的文本,但它没有发生。什么时候   我点击后退按钮我可以看到EditText上的文字发生了变化

我认为这是因为在LoadScreenHelper的{​​{1}}方法中使用onResume而发生这种情况。请注意,当活动进入前台时,将始终会调用FragmentActivity,这也会在onResume开始Activity后返回时发生。现在,通过调用startActivityForResult的{​​{1}}方法,您始终会向初始LoadScreenHelper添加新的loadTargetScreen()。当您从孩子MultiFormScreenFragment回来时,将再次调用FragmentActivity方法并创建新的Activity,最有可能覆盖最初添加的片段。如果单击后退按钮,将从屏幕中删除此顶部片段,并保留最初添加的片段。

由于我不知道你最后要用onResume课程做什么,我建议移动这条线:

MultiFormScreenFragment
LoadScreenHelper方法中

所以它只执行一次,或者在new LoadScreenHelper((FragmentActivity)context, R.id.fragment_container).loadTargetScreen("", 1,"",1,false,"","",""); 方法中插入一个检查,以确定onCreate的实例是否已经在布局中(使用loadTargetScreen查找片段)。如果它已经在布局中,则不执行任何其他操作添加片段的新实例。