将值从活动传递到片段

时间:2019-11-27 18:00:09

标签: android android-fragments

登录我的应用程序后,我正在使用导航抽屉。在导航抽屉中,我正在使用一个名为“配置文件”的片段来显示用户信息。我想将数据从登录页面活动传递到配置文件片段。

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);
}

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

2 个答案:

答案 0 :(得分:0)

您需要在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中获取您的工作方式。

您还应该在使用它的活动中创建片段。因此,如果它在您的home活​​动中,您将要传递登录活动中的数据,然后在onCreate中为该home活​​动构建片段。

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);

答案 1 :(得分:0)

在Kotlin中,您可以从这样的片段中访问活动变量

(activity as ActivityClassName).variableName

我在Java方面没有太多经验,但是我相信这是将代码翻译成Java的原因

((ActivityClassName) getActivity()).variableName