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!
问题:
回答1:
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.
回答2:
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");
回答3:
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);