Send String from an Activity to a Fragment of anot

2019-03-16 20:44发布

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条回答
爷、活的狠高调
2楼-- · 2019-03-16 21:11

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.

查看更多
Fickle 薄情
3楼-- · 2019-03-16 21:12

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");
查看更多
Deceive 欺骗
4楼-- · 2019-03-16 21:17

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);    
查看更多
登录 后发表回答