【问题标题】:How to refresh previous fragment after closing an activity?关闭活动后如何刷新上一个片段?
【发布时间】:2014-12-10 06:08:54
【问题描述】:

我有一个片段会引发一个活动,用户可以在其中插入一些细节。 当用户终止填充数据时,活动关闭。然后显示上一个片段,我希望它被更新(使用用户在活动中提供的数据)。

如果它是一个活动,而不是片段,我可以使用这个:

@Override
public void onResume(){
    super.onResume();
    recreate();
}

如何对片段做同样的事情?

【问题讨论】:

    标签: android fragment refresh back recreate


    【解决方案1】:

    您可以在片段中调用 startActivityForResult(Intent intent, int requestCode) 方法时抛出一个 Activity。

    你还需要在你的fragment中提供onActivityResult(int requestCode, int resultCode, Intent data),数据在Intent参数中。

    public class YourFragment extends Fragment {
    
         public void throwActivity() {
                // start activity
                Intent intent = new Intent();
                intent.setClass(getActivity(), YourActivity.class);
                int requestCode = 1;
                startActivityForResult(intent,requestCode);
            }
    
            // callback
            @Override
            public void onActivityResult (int requestCode, int resultCode, Intent data) {
    
                recreate();
    
            }
    
            public void recreate() {
                // your refresh code
            }
    }
    public class YourActivity extends Activity {
    
        public void yourMethod() {
    
               int resultCode = 2;
               setResult(resultCode);    // goback to your fragment with your data
            }
    }
    

    【讨论】:

    • 我不需要将数据从活动传递到片段。当我回到片段时,我需要它必须重新创建(重新启动)。
    • 对不起,我已经更新了我的问题,因为我错了。
    • 你能编辑你的代码吗?不需要数据从活动传递到片段?此外还有一些错误:第 3 行(缺少括号)、第 6 行(使用 getActivity() 代替 this)
    • 对不起,我在纯文本编辑器中输入了代码,我已经更新了上面的代码。
    • recreate方法要写什么?我必须在完成()之前使用 yourMethod() 吗?
    【解决方案2】:

    您将在此 Fragment 所属的 Activity 中覆盖 onResume,并在此 Activity 中重新创建(重新启动)此 Fragment。例如

    public class ActivityA extends Activity {
        @Override
        public void onResume() {
            //  here you can get the Fragment  instance , so you can recreated this fragment      here or invoke this fragment's function to set data or refresh data
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多