Send String from an Activity to a Fragment of another Activity

后端 未结 3 1170
醉酒成梦
醉酒成梦 2021-02-06 16:34

I have two Activities (A and B) and a Fragment F The Fragment F is contained in the Activity B I\'d like to send Strings from Activity A to Fragment F How can do that? Thanks!

相关标签:
3条回答
  • 2021-02-06 16:45

    First, you'll actually send that string to your activity B. For example:

    Intent intent = new Intent(this, YourActivityClass.class);
    intent.putExtra("myString", "this is your string");
    startActivity(intent);
    

    then later read that string from your activity B and inject into your fragment before executing the fragment-transaction. For example:

    Bundle args = new Bundle();
    args.putString("myString", getIntent().getExtras().getString("myString"))
    yourFragment.setArguments(args);
    

    Later, use getArguments() in your fragment to retrieve that bundle.


    Or alternatively, use the following in your fragment to directly access the activity intent and fetch your required value:

    String str = getActivity().getIntent().getStringExtra("myString");
    

    For more info, read this.

    0 讨论(0)
  • 2021-02-06 16:45

    In Fragment.java file add the following code,

    public static String name= null;
    
    public void setName(String string){
    name = string;
    }
    

    In MainActivity.java from which you want to send String add the following code,

    String stringYouWantToSend;
    
    Fragment fragment =  new Fragment();
    fragment.setName(stringYouWantToSend);    
    
    0 讨论(0)
  • 2021-02-06 17:02

    It is Almost same as you would exchange data between activities. you should just use getActivity() in the beginning in order to access in fragments.

    check below code:

    In Activity A:

    Intent intent = new Intent(this,ActivityB.class);
    intent.putExtra("data",data); //data is a string variable holding some value.
    startActivity(intent); 
    

    In fragment F of Activity B

    String data = getActivity().getIntent().getStringExtra("data");
    
    0 讨论(0)
提交回复
热议问题