android - 将值从 Activity 传递到 Fragment
问题描述
登录我的应用程序后,我正在使用导航抽屉。在导航抽屉中,我使用了一个名为“配置文件”的片段来显示用户信息。我想将数据从登录页面活动传递到配置文件片段。
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 中所做的参数。
您还应该在使用它的活动中创建片段。因此,如果它在您的家庭活动中,您将希望从登录活动中传递数据,然后在 onCreate 中为家庭活动构建片段。
Intent home = new Intent(this, HomeActivity.class);
intent.putExtra("name", gname);
startActivity(home);
在 HomeActivity
Bundle extras = getIntent().getExtras();
String gname = extras.getString("name");
Profile profile = Profile.newInstance(gname);
推荐阅读
- r - 按数据框列汇总行,然后将这些行转换为列
- python - python - 如何在python中将一个充满图像的目录调整为所需的宽度和高度?
- python - 数据框将带有数组的列拆分为多行
- java - 是对象c;然后 c = new Integer(0); 合法的?
- laravel - Laravel - 聚合函数中的语法错误或访问冲突
- python - 一次使用两个线程池
- python - 使用格式将字符串转换为日期时间
- xcode - Xcode 11 beta:AppDelegate 文件没有窗口全局变量
- swift - 谁能解释一下 Swift Combine 的 Subject.eraseToAnySubject() 方法以及应该在哪里使用它?
- asp.net - Webconfig URL 重写以隐藏经典 ASP ext 但不是 .aspx 或其他 ext