本文介绍了安卓:从子片段将数据传递到父片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从子片段父片段,我就可以当我回到父母的片段读通过一些数据。详细:

I need to pass some data from the child fragment to the parent fragment that I will be able to read when I go back to the parent fragment. In detail:

我有一个FragmentActivity调用FragmentParent。从FragmentParent我叫FragmentChild是这样的:

I have a FragmentActivity that calls FragmentParent. From FragmentParent I call FragmentChild like this:

FragmentChild fragmentChild = new FragmentChild();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frl_view_container, fragmentChild);
transaction.addToBackStack(null);
ctransaction.commit();

在FragmentChild我设置一个字符串值,我需要传递回FragmentParent然后我返回到FragmentParent。

In FragmentChild I set a string value which I need to pass back to FragmentParent and then I return back to FragmentParent.

String result = "OK";
getFragmentManager().popBackStack();

什么是最好/有道阅读FragmentParent结果字符串?

What is the best/proper way to read the result string in FragmentParent?

推荐答案

您可以使用 setTargetFragment 和 onActivityResult 以实现这一目标。

You can use setTargetFragment and onActivityResult to achieve this.

设置FragmentParent实例作为FragmentChild实例目的片段即

Set FragmentParent instance as target fragment on FragmentChild instance i.e.

FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setTargetFragment(this, FRAGMENT_CODE);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frl_view_container, fragmentChild);
transaction.addToBackStack(null);
transaction.commit();

在FragmentChild,无论你调用的popBackStack,呼吁onActivityResult所设定的目标片段。使用捆绑传递更多的数据。

In FragmentChild, wherever you are invoking the popBackStack, call onActivityResult on the set target Fragment. Use Bundle to pass on additional data.

Intent intent = new Intent();
intent.putExtra(FRAGMENT_KEY, "Ok");
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
getFragmentManager().popBackStack();

早在FragmentParent,覆盖默认onActivityResult方法。

Back in FragmentParent, override the default onActivityResult method.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == FRAGMENT_CODE && resultCode == Activity.RESULT_OK) {
        if(data != null) {
           String value = data.getStringExtra(FRAGMENT_KEY);
           if(value != null) {
              Log.v(TAG, "Data passed from Child fragment = " + value);
           }
        }
    }
}  

这篇关于安卓:从子片段将数据传递到父片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 08:55