Transferring data from one fragment to another

I have an Activity with two fragments, and I need to pass a string from FragmentA to FragmentB.

To pass the data, I have this in my FragmentA:

    Intent intent = new Intent(getActivity(), FragmentB.class);
    intent.putExtra("name", "Mark");
    startActivity(intent);

And to get the data, I did it in FragmentB

    Intent intent = getActivity().getIntent();
    Bundle b = intent.getExtras();

    if(b!=null)
    {
        String name =(String) b.get("name");
        nameTextView.setText(name);
    }

But that does not work. Is there a way to pass a string from one fragment to another fragment?

+4
source share
4 answers
  • , . , . , , String Activity. A B.
  • , putExtra A A B. Activity B B.
+14

, setArguments(Bundle b). :

public class FragmentA extends Fragment {

  public static FragmentA newInstance(String name) {
    Bundle bundle = new Bundle();
    bundle.putString("name", name);
    FragmentA f = new FragmentA(); 
    f.setArguments(bundle);
    return f;
  }

}
+4

You can do something like below

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

To retrieve data, follow these steps:

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

Code in FragmentActivity 1 fragment A:

fb is an instance of the created bean, and ID is a parameter

Intent intent = new Intent(getContext(), FragmentActivity2.class);
        intent.putExtra("id", fb.ID);
startActivity(intent);

Code in fragment FragmentActivity 2 Any:

fragmentA= (FragmentActivity2) getActivity();
String cust_id = fragmentA.getIntent().getExtras().getString("id");
0
source

Source: https://habr.com/ru/post/1532898/


All Articles