如何在 Android 中将值从一个 Fragment 传递到另一个?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23250707/
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 06:56:51  来源:igfitidea点击:

How to pass a value from one Fragment to another in Android?

androidandroid-fragmentsbundle

提问by anu_r

I am a newbie to Fragments. I want to pass a String value from one Fragment to another. how to do this? I have called my Fragments in the following way. please guide me step by step.

我是 Fragments 的新手。我想将一个字符串值从一个片段传递到另一个片段。这该怎么做?我用以下方式调用了我的 Fragments。请一步一步指导我。

String cid = id.getText().toString();
Fragment fr = new FriendFragment();
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fr);
ft.commit(); 

回答by Spring Breaker

You can do something like below,

您可以执行以下操作,

 String cid=id.getText().toString();
 Fragment fr=new friendfragment();
 FragmentManager fm=getFragmentManager();
 android.app.FragmentTransaction ft=fm.beginTransaction();
 Bundle args = new Bundle();
 args.putString("CID", cid);
 fr.setArguments(args);
 ft.replace(R.id.content_frame, fr);
 ft.commit(); 

To receive the data do the following,

要接收数据,请执行以下操作,

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("CID");    
    return inflater.inflate(R.layout.fragment, container, false);
}

回答by Midhun Vijayakumar

If you want to send data from fragment to activity you may use an interface.

如果您想将数据从片段发送到活动,您可以使用接口。

But when you want to send data from fragment to another fragment it get's complicated. You would want to send data to activity and then to the other fragment.

但是当你想将数据从片段发送到另一个片段时,它变得很复杂。您可能希望将数据发送到活动,然后再发送到另一个片段。

I use EventBusto solve this problem. How it works.

我使用EventBus来解决这个问题。这个怎么运作。

  1. Create an event-E.
  2. From Fragment-A register for events.
  3. From fragment-B publish event-E with data you want to pass.
  4. You would get the data in onEvent() method you wrote in Fragment-A.
  1. 创建一个事件-E。
  2. 从 Fragment-A 注册事件。
  3. 从片段-B 发布带有要传递的数据的事件-E。
  4. 您将在您在 Fragment-A 中编写的 onEvent() 方法中获取数据。

That's it. No need to write your own interfaces.

就是这样。无需编写自己的接口。

You may use eventbus for communications from background service or threads to activity also.

您也可以使用 eventbus 进行从后台服务或线程到活动的通信。

Checkout the EventBus HowToand Repositoryalso.

还可以查看EventBus HowToRepository

回答by Jaydeep Dobariya

try this :

- send data : 

        Bundle arg = new Bundle();
        arg.putInt("ID", "12");  //arg.putInt("KEY", "VALUE")
        arg.putString("NAME","Jaydeep");//arg.putString("KEY","VALUE")

        YourFragment fragment = new YourFragment();
        fragment.setArguments(arg);

        fragmentManager.beginTransaction().add("PUT YOUR FRAM ID", fragment, fragment.getClass().getName())
        .addToBackStack(null)
        .commit();

- receive data : 

        Bundle bundle = getIntent().getExtras();
        bundle.getInt("ID");
        bundle.getString("NAME");

        Log.e("Receive data : " ,"\nID - "+bundle.getInt("ID")+"\nNAME - "+bundle.getString("NAME"));

回答by Dinesh Sarma

you can try this

你可以试试这个

First Fragment

第一个片段

//adding data to the bundle class
Bundle b = new Bundle();
b.putString("user_name","simon");
b.putString("user_address","nepal");
//fragment operation
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment fragment=new friendfragment();
fragment.setArguments(b);
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();

//Second Fragment(Receiving Fragment)
//write following code into onCreateView() method
Bundle b = getArguments();
String name = b.getString("user_name");
String address = b.getString("user_address");

回答by siriD

Fragment to Fragment communication must be done through the parent Activity.

Fragment 到 Fragment 的通信必须通过父 Activity 完成。

FragmentToSendData

FragmentToSendData

interface <interfaceName>{
    void <abstract method>(String str);
}

@Override
public void onAttach(Activity activity) {
        super.onAttach(activity);
       try{
           <instance of the interface> = (<interface>)getActivity();
       }catch (ClassCastException e) {
           throw new ClassCastException(getActivity().toString()
                   + " must implement <interface>");
       }

    }

ActivityWithBothFragments(this can be through ViewPager, or use the id of your fragment, just use findFragmentById() )

ActivityWithBothFragments(这可以通过 ViewPager,或使用片段的 id,只需使用 findFragmentById() )

@Override <abstract method from frag1>(String str){
  FragmentToReceiveData fragment2 =  (FragmentToReceiveData)getSupportFragmentManager().findFragmentByTag(ViewPagerAdapter.getFragmentTag(1));                                                                                                                                                

    fragment2.getStringFromFrag1(String str);
}

FragmentToReceiveData

接收数据的片段

public void getStringFromFrag1(String str){
  <textview>.setText("str");

}