如何在Android中将意图从活动传递到片段 [英] How to pass intent from activity to fragment in Android
问题描述
您好,Android初学者如何将Activity的意图赋予片段? 我知道像这样从片段到活动
Hello am new to Android how to give intent from Activity to fragment? I know from Fragment to Activity like this
Intent intent=new Intent(getActivity(),nextActivity.class)
StartActivity(intent);
但是我想要从Activity到Fragment.
But I want from Activity to Fragment.
推荐答案
您不能将意图传递给片段,您可以做的就是获取意图中包含的数据并将其传递给片段.推荐的方法是使用newInstance模式. 因此,在片段中您将拥有以下内容:
You cannot pass the intent to the fragment, what you can do is get the data you have in the intent and pass it to the fragment. The recommended way to do that is to use the newInstance pattern. So in the fragment you'll have this:
public static MyFragment newInstance(@NonNull final String someId) {
final MyFragment fragment = new ProfileFragment();
final Bundle args = new Bundle();
args.putString(Const.KEY_SOME_ID, someId);
fragment.setArguments(args);
return fragment;
}
要创建片段,您当然要调用该方法.
To create the fragment of course you'll call that method.
String id = getIntent().getStringExtra(Const.KEY_ID);
MyFragment fragment = MyFragment.newInstance(id);
并在需要从参数中获取的片段中访问它:
and to access it inside the fragment you need to get from arguments:
Bundle args = getArguments();
if (args != null) {
myId = args.getString(Const.KEY_SOME_ID, "");
}
这篇关于如何在Android中将意图从活动传递到片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!