如何将数据从一个片段传输到另一个片段android

时间:2013-10-12 10:31:28

标签: android fragment

我知道的一种方式是通过activity.We可以从片段发送数据到活动和活动到片段有没有其他方式。

5 个答案:

答案 0 :(得分:14)

将数据从一个片段传递到另一个片段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);

答案 1 :(得分:5)

从文档引用

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

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

有关更多信息和示例chekc以下链接中的文档

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

答案 2 :(得分:4)

我认为有两种方法可行:

A 。与你自己的活动沟通,并通过该拥有的活动将消息转发给其他片段,详细信息可以在官方的Android文档中找到:

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

<强>引用:

  

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

通信界面可能如下所示:

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.");
        }
    }
}

我在这里使用的是WeakReference,但这真的取决于你。您现在可以使用actionCallback与拥有活动进行通信,并调用IActionListener中定义的方法。

拥有的活动看起来像这样:

public class MyActivity extends ActionBarActivity implements IActionListener {

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

}

<强>乙即可。现在对于第二种方法 - 您可以使用接口让片段直接相互通信 - 这样您就不必知道要与之交谈的片段的确切类别,确保松耦合。

设置如下:您有两个片段(或更多)和一个活动(以启动第二个片段)。我们有一个界面,让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.片段1中描述的方法,要求它拥有Activity来启动片段2.但是,Activity会将片段1作为参数传递给片段2,因此片段2可以稍后间接访问片段1并发送回复。让我们来看看Activity如何准备片段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();
        }
    }

提示:我正在使用支持框架,因此,如果您仅为&gt;开发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()的实现。

答案 3 :(得分:2)

这是解决方案,

按照以下步骤操作:

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.现在,在Fragment中写一些代码。

          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
             }

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

答案 4 :(得分:0)

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

相关问题