将值从活动传递到片段

问题描述 投票:0回答:1

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

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

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

android android-fragments
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.