[英]Passing values from Activity to Fragment
登录我的应用程序后,我正在使用导航抽屉。 在 Navigation drawer 中,我使用了一个名为“profile”的片段来显示用户信息。 我想将数据从登录页面活动传递到配置文件片段。
Bundle bundle = new Bundle();
Intent home = new Intent(LoginPage.this, HomeActivity.class);
startActivity(home);
bundle.putString("name", gname);
Profile profile = new Profile();
profile.setArguments(bundle);
这是我的个人资料片段:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
name = this.getArguments().getString("name");
ntext.setText(name);
return inflater.inflate(R.layout.activity_profile, container, false);
}
但我收到空指针异常。 我不明白有什么问题! 如果有另一种方法可以将数据从活动传递到片段,请告诉我!
您需要在 Profile 片段中创建一个名为 newInstance 的函数,该函数创建片段并通过那里设置参数,然后返回带有参数的片段。 像这样
public static Profile newInstance(String name){
Profile profile = new Profile();
Bundle bundle = new Bundle();
bundle.putString("name", name);
profile.setArguments(bundle);
return profile;
}
然后像这样在您的活动中创建片段
Profile profile = Profile.newInstance(gname);
并获取您在片段中的 onCreate 中所做的参数。
您还应该在您正在使用它的活动中创建 Fragment。因此,如果它在您的家庭活动中,您将希望传递来自登录活动的数据,然后在 onCreate 中为家庭活动构建片段。
Intent home = new Intent(this, HomeActivity.class);
intent.putExtra("name", gname);
startActivity(home);
在家庭活动中
Bundle extras = getIntent().getExtras();
String gname = extras.getString("name");
Profile profile = Profile.newInstance(gname);
在 Kotlin 中,您可以像这样从片段访问活动变量
(activity as ActivityClassName).variableName
我在Java方面没有太多经验,但我相信这是将代码翻译成Java
((ActivityClassName) getActivity()).variableName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.