简体   繁体   English

如何将数据从片段传递到另一个片段?

[英]How to pass data from fragment to another fragment?

I have tried several times to send data from one fragment to another and it never works.我曾多次尝试将数据从一个片段发送到另一个片段,但它从来没有奏效。 I already used "Intent" and "Bundle" but nothing works.我已经使用了“Intent”和“Bundle”,但没有任何效果。 They said to use BroadCast Receiver, but there is little information on the Internet.他们说要用BroadCast Receiver,但网上资料很少。 Can anyone give me an example?谁能给我一个例子?

There is no intent passing concept in fragment communication, fragments only accepts the arguments instead.分片通信中没有intent传递的概念,分片只接受arguments代替。 Here is an simple example of fragment communication using bundle :这是一个使用bundle进行片段通信的简单示例:

  YourReceiverFragment newFragment = new YourReceiverFragment();
  Bundle args = new Bundle();
  args.putString("key1", data1);
  args.putString("key2", data1);
  newFragment.setArguments(args);

And get it from another (receiver) fragment inside the onCreateView() like:并从onCreateView()中的另一个(接收器)片段中获取它,例如:

String value1 = getArguments().getString("key1");
// and so on

But, Another good practice for fragment to fragment communication is to use interfaces via Activity like:但是,片段到片段通信的另一个好习惯是通过Activity使用interfaces ,例如:

SenderFragment :发件人片段

    public class SenderFragment extends Fragment {

    SenderFragmentListener mCommunication;
    public SenderFragment() {}// Required empty public constructor

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mCommunication = (SenderFragmentListener) context;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sender, container, false);
        Button button = (Button) view.findViewById(R.id.btn_sender);
        // on click button
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCommunication.messageFromSenderFragment("Hello Fragment i am Sender...");
            }
        });
        return view;
    }
    //Interface for communication
    public interface SenderFragmentListener {
        void messageFromSenderFragment(String msg);
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mCommunication = null;
    }
}

Activity :活动

    public class MainActivity extends AppCompatActivity implements 
        SenderFragment.SenderFragmentListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public void messageFromSenderFragment(String msg) {
        FragmentManager manager = getSupportFragmentManager();
        ReceiverFragment mReceiverFragment = (ReceiverFragment)manager.findFragmentById(R.id.frg_Receiver);
        mReceiverFragment.youGotMsg(msg);
    }
}

ReceiverFragment :接收器片段

    public class ReceiverFragment extends Fragment {

    TextView tv_msg;

    public ReceiverFragment(){} // Required empty public constructor

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_receiver, container, false);
        tv_msg = (TextView) view.findViewById(R.id.tv_receiver);
        return view;
    }
    //Receive message
    public void youGotMsg(String msg) {
        tv_msg.setText(msg);
    }
}

Let me know if it helps.让我知道它是否有帮助。

Fragments don't communicate directly unless you use viewmodels.除非您使用视图模型,否则片段不会直接通信。 Here is a guide that can help you get started in working with fragments这是一个可以帮助您开始使用片段的指南

https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments

you can use viewmodel to share data between fragments, you can see detail in repo: enter link description here您可以使用 viewmodel 在片段之间共享数据,您可以在 repo 中查看详细信息: 在此处输入链接描述

Data can be passed between fragments using bundle可以使用 bundle 在片段之间传递数据

You have to write this in place where you are trying to change the fragment你必须在你试图改变片段的地方写这个

Bundle bundle = new Bundle();
bundle.putInt("key_name1", value1);
bundle.putString("key_name2", value2);


FragmentB fragmentB = new FragmentB();
fragmentB.setArguments(bundle);

In FragmentB you can receive this data (you can write this in the onViewCreated() lifecycle of the fragment):在 FragmentB 中,您可以接收此数据(您可以在片段的 onViewCreated() 生命周期中编写此数据):

Bundle bundle = this.getArguments();
if (bundle != null) {

value1=bundle.getInt("key_name1", 0); //0 is the default value , you can change that
value2=bundle.getString("key_name2",""); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM