Android 如何将结果从第二个片段传递到第一个片段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12103953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:44:24  来源:igfitidea点击:

How to pass result from second fragment to first fragment

androidandroid-fragments

提问by abhishek

In my app I have two fragments say fragmentAand FragmentB. When I click on a button in fragmetA, a list is opened in fragmentB. Now when I select an item from list in fragmentBI want the result to be passed to fragmentA. I am using only one TabActivity for all fragments. When list item is selected in fragmentBI am popping out fragmentBfrom stack so that I can directly go back to fragmentA.

在我的应用程序中,我有两个片段说fragmentAFragmentB。当我单击fragmetA 中的按钮时,会在fragmentB 中打开一个列表。现在,当我从fragmentB 的列表中选择一个项目时,我希望将结果传递给fragmentA。我只对所有片段使用一个 TabActivity。当在fragmentB 中选择列表项时,我从堆栈中弹出fragmentB以便我可以直接返回到fragmentA

Does anyone knows how to pass result to previous fragment.

有谁知道如何将结果传递给上一个片段。

Thanks.

谢谢。

采纳答案by S.D.

Update

更新

Activity is the parent controllerand should take responsibility for handling those events raised by its fragments/views, which concern something outside of the scope of fragment/view itself.

Activity 是父控制器,应该负责处理由其片段/视图引发的事件,这些事件涉及片段/视图本身范围之外的内容。

A Fragment is to act as a sub-controllerof Views it hosts. All the events and communication between its own views, the fragment should handle itself. When there is an event outside of a fragment's scope and responsibilities (like sending data to another fragment), that event should be escalated to its parent controller, the Activity.

Fragment 将充当其托管的 Views的子控制器。所有事件和它自己的视图之间的通信,片段应该自己处理。当有一个片段的范围和职责之外的事件(比如向另一个片段发送数据)时,该事件应该被升级到它的父控制器,即活动。

enter image description here

在此处输入图片说明

Old

老的

From this tutorial : http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

从本教程:http: //developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

Its better to let the activity apply changes to its fragment than passing values directly between fragments. Let your Activity implement a FragmentListenerinterface with onQuery(Bundle data)and onResult(Bundle data)methods.

让活动对其片段应用更改比直接在片段之间传递值更好。让你的 Activity 实现一个FragmentListener接口onQuery(Bundle data)onResult(Bundle data)方法。

Create a FragmentListenervaraible in each of your fragments and then override onAttach()of each fragment as:

FragmentListener在每个片段中创建一个变量,然后onAttach()将每个片段覆盖为:

 public void onAttach(Activity activity) {
    super.onAttach(activity);

    //---register parent activity for events---
    try{
        fragmentListener = (FragmentListener) activity;
    }catch (ClassCastException e)
    {
        throw new ClassCastException("Parent activity must implement interface FragmentListener.");
    }
  }

This will enforce your child fragments to be automatically registered to parent Activity.

这将强制您的子片段自动注册到父 Activity。

Also, remember to release fragmentListenerreference in onDetach().

另外,记得fragmentListeneronDetach().

Now you can call your Activity from fragments.

现在您可以从片段中调用您的 Activity。

On the other side, your Activity can always search for a fragment using getFragmentManager().findFragmentByTag("fragmentA")or findFragmentById("FragmentA"). If it can find your Fragment, Then it can cast it into your FragmentAclass and call its methods. Same can be done with FragmentBor any other fragment..

另一方面,您的 Activity 始终可以使用getFragmentManager().findFragmentByTag("fragmentA")或搜索片段findFragmentById("FragmentA")。如果它可以找到您的 Fragment,那么它可以将其转换为您的FragmentA类并调用其方法。同样可以用FragmentB或任何其他片段来完成..

回答by Fedor Kazakov

One of the possible solutions:

可能的解决方案之一:

public class DetachableResultReceiver extends ResultReceiver {

private Receiver mReceiver;

public DetachableResultReceiver(Handler handler) {
    super(handler);
}

public void clearReceiver() {
    mReceiver = null;
}

public void setReceiver(Receiver receiver) {
    mReceiver = receiver;
}

public interface Receiver {
    public void onReceiveResult(int resultCode, Bundle resultData);
}

@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
    if (mReceiver != null) {
        mReceiver.onReceiveResult(resultCode, resultData);
    }
}
}

First fragment implements DetachableResultReceiver.Receiver and creates DetachableResultReceiver object:

第一个片段实现 DetachableResultReceiver.Receiver 并创建 DetachableResultReceiver 对象:

mReceiver = new DetachableResultReceiver(new Handler());
mReceiver.setReceiver(this);

Then you can pass it to second fragment arguments:

然后你可以将它传递给第二个片段参数:

Bundle bundle = new Bundle();
bundle.putParcelable(Consts.EXTRA_RECEIVER, receiver);
fragment.setArguments(bundle);

And use it in second fragment:

并在第二个片段中使用它:

receiver = getArguments().getParcelable(Consts.EXTRA_RECEIVER);
receiver.send(Consts.SOME_MESSAGE, someData);

回答by CoolMind

You can also use SharedPreferencesto save some string and after return back to the first fragment load it and clear.

您还可以使用SharedPreferences来保存一些字符串,并在返回到第一个片段后加载并清除。

回答by EGHDK

In fragmentB.java set an OnClickListener to perform a method in the main class. Pass an arguement in fragmentB.java to the main class that is the variable, and handle the rest of it in your main class. Though fragments shouldn't really be dependent on activities at all. Fragments were made to plug and play anywhere.

在 fragmentB.java 中设置一个 OnClickListener 来执行主类中的方法。将 fragmentB.java 中的参数传递给作为变量的主类,并在主类中处理其余部分。尽管片段根本不应该真正依赖于活动。Fragment 可以在任何地方即插即用。

This Example Shows EditTextListener:

此示例显示 EditTextListener:

myAwesomeActivity.java

我的AwesomeActivity.java

fragmentA.java

片段A.java

fragmentB.java

片段B.java

fragmentB.java:

片段B.java:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
            int x = 3;

        EditText ed1 = (EditText) getView().findViewById(R.id.editText1);
        ed1.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_UP == event.getAction()) {



                    ((myAwesomeActivity) getActivity()).myMethod(x);
                }
                return false;
            }
        });
    }

myAwesomeActivity.java:

myAwesomeActivity.java:

publiv void myMethod (int x){
//Do whatever you want with variable
}

All you have to do is implement the correct type of listener, but the main point is shown. In one fragment activity, call a method and pass a variable to the main activity. From the main activity you can send it to your other fragment activity if you'd like.

您所要做的就是实现正确类型的侦听器,但显示了要点。在一个片段活动中,调用一个方法并将一个变量传递给主活动。如果您愿意,您可以将其从主要活动发送到其他片段活动。