【问题标题】:How can I transfer data from one fragment to another fragment android如何将数据从一个片段传输到另一个片段android
【发布时间】:2013-10-20 10:06:56
【问题描述】:

我知道的一种方法是通过活动。我们可以将数据从片段发送到活动,将活动发送到片段有没有其他方法。

【问题讨论】:

标签: android fragment


【解决方案1】:

将数据从一个片段传递到另一个片段Bundle 会有所帮助。

LifeShapeDetailsFragment fragment = new LifeShapeDetailsFragment(); //  object of next fragment
Bundle bundle = new Bundle();
bundle.putInt("position", id);
 fragment.setArguments(bundle);

然后push/call next Fragments.

和代码到下一个片段:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt("position", 0);

【讨论】:

【解决方案2】:

引用自文档

您通常希望一个 Fragment 与另一个 Fragment 进行通信,例如根据用户事件更改内容。 所有 Fragment 到 Fragment 的通信都是通过关联的 Activity 完成的。两个 Fragment 永远不应该直接通信。

我建议你按照文档中的方法,我还没有尝试过任何其他替代方法

有关更多信息和示例,请查看以下链接中的文档

http://developer.android.com/training/basics/fragments/communicating.html

【讨论】:

【解决方案3】:

我认为有两种方法可行:

A。与您拥有的 Activity 通信并通过该拥有的 Activity 将消息转发到其他 Fragment,详细信息可以在此处的官方 android 文档中找到:

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

引用:

在某些情况下,您可能需要一个片段来与 活动。一个很好的方法是定义一个回调接口 在片段内部并要求宿主活动实现它。 当activity通过接口接收到回调时,它可以 根据需要与布局中的其他片段共享信息。

通信接口可能如下所示:

public interface IActionListener{

  //You can also add parameters to pass along etc
  public void doSomething();
}

片段看起来像这样:

public class MyFragment extends Fragment{

private WeakReference<IActionListener> actionCallback;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            // This makes sure that the container activity has implemented
            // the callback interface. If not, it throws an exception
            actionCallback = new WeakReference<IActionListener>((IActionListener) activity);
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement IActionListener.");
        }
    }
}

我在这里使用 Wea​​kReference,但这完全取决于您。您现在可以使用 actionCallback 与拥有的 Activity 进行通信并调用 IActionListener 中定义的方法。

拥有的 Activity 如下所示:

public class MyActivity extends ActionBarActivity implements IActionListener {

public void doSomething(){ //Here you can forward information to other fragments }

}

B。现在至于 第二种方法 - 您也可以让片段直接使用接口相互通信 - 这样您就不必知道您正在与之交谈的片段的确切类,这可以确保松耦合。

设置如下:您有两个(或更多)片段和一个活动(启动第二个片段)。我们有一个接口,它可以让 Fragment 2 在完成任务后向 Fragment 1 发送响应。为了简单起见,我们只是重用了我在 A.

中定义的接口

这是我们的片段 1:

public class FragmentOne extends Fragment implements IActionListener {

 public void doSomething() {//The response from Fragment 2 will be processed here}

}

使用 A. Fragment 1 中描述的方法要求其拥有的 Activity 启动 Fragment 2。但是,Activity 会将 Fragment 1 作为参数传递给 Fragment 2,因此 Fragment 2 稍后可以间接访问 Fragment 1 并发送回复.让我们看看 Activity 是如何准备 Fragment 2 的:

    public class MyActivity extends ActionBarActivity {

    // The number is pretty random, we just need a request code to identify our request later
    public final int REQUEST_CODE = 10;
    //We use this to identify a fragment by tag
    public final String FRAGMENT_TAG = "MyFragmentTag";

        @Override
        public void onStartFragmentTwo() {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();

                    // The requesting fragment (you must have originally added Fragment 1 using 
                    //this Tag !)
            Fragment requester = manager.findFragmentByTag(FRAGMENT_TAG);   
                    // Prepare the target fragment
            Fragment target = new FragmentTwo();
                    //Here we set the Fragment 1 as the target fragment of Fragment 2's       
                    //communication endeavors
            target.getSelf().setTargetFragment(requester, REQUEST_CODE);

                    // Hide the requesting fragment, so we can go fullscreen on the target
            transaction.hide(requester);
            transaction.add(R.id.fragment_container, target.getSelf(), FRAGMENT_TAG);
            transaction.addToBackStack(null);

            transaction.commit();
        }
    }

提示:我正在使用 Support-Framework,所以如果您只为 > Android 3.0 开发,您可以简单地使用 FragmentActivity 而不是 ActionBarActivity。

现在 FragmentTwo 正在启动,让我们看看 FragmentTwo 将如何与 FragmentOne 通信:

public class FragmentTwo extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(savedInstanceState != null){
            // Restore our target fragment that we previously saved in onSaveInstanceState
            setTargetFragment(getActivity().getSupportFragmentManager().getFragment(savedInstanceState, TAG),
                    MyActivity.REQUEST_CODE);           
        }

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Retain our callback fragment, the TAG is just a key by which we later access the fragment
        getActivity().getSupportFragmentManager().putFragment(outState, TAG, getTargetFragment());
    }

    public void onSave(){
        //This gets called, when the fragment has done all its work and is ready to send the reply to Fragment 1
        IActionListener callback = (IActionListener) getTargetFragment();
        callback.doSomething();
    }

}

现在将调用 Fragment 1 中的 doSomething() 实现。

【讨论】:

  • 我认为您的第一个代码摘录中存在代码错误。您在某一时刻调用您的 WeakReference “ActionListener”,在另一时刻调用“ActionCallback”。你能检查一下吗?
  • @ParthShah 哦,谢谢!把这个写在我的脑海里,并且没有仔细检查变量名 - 再次感谢你,我更正了它
  • 尽管如此,答案非常好,有很多很好的例子!干得好!
【解决方案4】:

这是解决方案,

按照以下步骤操作:

1 创建这样的界面

     public interface TitleChangeListener
      {
       public void onUpdateTitle(String title);
      }

2.使用此接口实现您的活动

    for.e.g 
    public class OrderDetail extends ActionBarActivity  implements TitleChangeListener

3.在这个活动中创建 onUpdateTitle()

        public void onUpdateTitle(String title)
        {
         //here orderCompletedDetail is the object second fragment name ,In which fragement I want send data.

         orderCompletedDetail.setTitle(title);
         }

4.现在,在片段一中编写一些代码。

          public class OrderPendingDetail extends Fragment
          {
          private View rootView;
          private Context context;
          private OrderDetail orderDetail;
          @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,    Bundle savedInstanceState)
            {
             rootView = inflater.inflate(R.layout.order_pending_detail, container, false);
            context = rootView.getContext();

            //here OrderDetail is the name of ActionBarActivity 
            orderDetail = (OrderDetail) context;

         //here pass some text to second Fragment using button ClickListener
           but_updateOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) 
               {
                // here call to Activity onUpdateTitle()
                orderDetail.onUpdateTitle("bridal");
                }
        });
        return rootView;
         }
         }

5.在第二个Fragment setTitle()中写一些代码

            public void setTitle(String title)
             {
             TextView orderCompeted_name=(TextView)rootView.findViewById(R.id.textView_orderCompeted_name);
             orderCompeted_name.setText(title);
             //here you see the "bridal" value for TextView
             }

在此解决方案中,当您单击 Fragment one 的按钮时,它会在第二个 Fragment 中显示值。 希望对你有帮助..!!

【讨论】:

    【解决方案5】:

    在使用 Fragment 时,允许 Fragment 通过使用 Activity 作为它们的中介来相互通信是一种常见的最佳实践。访问http://developer.android.com/guide/components/fragments.html 了解有关此重要模式的更多详细信息。每当您需要与另一个片段交互时,您应该始终在片段的活动中使用方法,而不是 直接访问另一个片段。从另一个片段访问一个片段唯一有意义的时候是当您知道您不需要在另一个活动中重用您的片段时。您几乎总是应该假设您将重用它们而不是硬编码它们彼此来编写片段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多