将数据从 Activity 传递到片段
Pass data from an Activity to a fragment
我对此有点迷茫,所以我已经将数据从我的 LoginActivity 传递到我的 DashboardActivity。它现在有效(感谢上帝)。但是现在,我很想将该数据传递给片段。
我的 DashboardActivity 上有这个:
Intent get = getIntent();
String userId = get.getStringExtra(LoginActivity.EXTRA_ID);
Bundle bundle = new Bundle();
bundle.putString("userId", userId);
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
我的 Fragment 上有这个:
Bundle bundle = getArguments();
String userId = bundle.getString("userId");
int uid = Integer.parseInt(userId);
是这样的吗?
从 activity 到片段你应该使用如下的 bundle
Bundle bundle = new Bundle();
bundle.putString(LoginActivity.EXTRA_ID, "Extra value");
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
然后在您的 Fragment 中,例如在 onCreate()
方法中获取数据
Bundle bundle = this.getArguments();
if (bundle != null) {
String extraId = bundle.getString(key, defaultValue);
}
在Fragment中获取数据和Activity的方法不一样。
要向片段发送额外内容,您可以这样做。
在你的ActivityClass
Bundle bundle = new Bundle();
bundle.putString("userId", "value you want to send");
FragmentClass frag = new FragmentClass();
frag.setArguments(bundle);
然后在Fragement onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("userId");
return inflater.inflate(R.layout.fragment, container, false);
}
您的代码的问题是您获取的参数 ID 错误。
正确的方式
String userId = getArguments().getString("userId");
我对此有点迷茫,所以我已经将数据从我的 LoginActivity 传递到我的 DashboardActivity。它现在有效(感谢上帝)。但是现在,我很想将该数据传递给片段。
我的 DashboardActivity 上有这个:
Intent get = getIntent();
String userId = get.getStringExtra(LoginActivity.EXTRA_ID);
Bundle bundle = new Bundle();
bundle.putString("userId", userId);
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
我的 Fragment 上有这个:
Bundle bundle = getArguments();
String userId = bundle.getString("userId");
int uid = Integer.parseInt(userId);
是这样的吗?
从 activity 到片段你应该使用如下的 bundle
Bundle bundle = new Bundle();
bundle.putString(LoginActivity.EXTRA_ID, "Extra value");
Fragment fragment = new Fragment();
fragment.setArguments(bundle);
然后在您的 Fragment 中,例如在 onCreate()
方法中获取数据
Bundle bundle = this.getArguments();
if (bundle != null) {
String extraId = bundle.getString(key, defaultValue);
}
在Fragment中获取数据和Activity的方法不一样。 要向片段发送额外内容,您可以这样做。
在你的ActivityClass
Bundle bundle = new Bundle();
bundle.putString("userId", "value you want to send");
FragmentClass frag = new FragmentClass();
frag.setArguments(bundle);
然后在Fragement onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("userId");
return inflater.inflate(R.layout.fragment, container, false);
}
您的代码的问题是您获取的参数 ID 错误。
正确的方式
String userId = getArguments().getString("userId");