首页 > 解决方案 > 将值从 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);
}

但我得到空指针异常。我不明白是什么问题!如果有另一种方法将数据从活动传递到片段,请告诉我!

标签: androidandroid-fragments

解决方案


您需要在 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);

推荐阅读