使用 bundle 在 tablayout 之间传递数据
Passing data by using bundle between tablayout
我正在使用 Bundle 从我的第一个 TabFragment
传递数据,但它提示 NullPointerException
。当 getArguments()
in list_fragments2
in second tab
时发生错误
MainActivity 片段
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
Toast.makeText(this, "" + b, Toast.LENGTH_SHORT).show();
SecondActivity 片段
public class list_fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View h = inflater.inflate(R.layout.tab2, container, false);
TextView textView = (TextView) h.findViewById(R.id.textView);
Bundle bundle=getArguments();
//your string
if(bundle != null) {
String test = bundle.getString("test");
textView.setText(test);
}
return h;
}
}
你真的加载了你的第二个片段吗?
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
fragmentTransaction.replace(placeholder, fragment);
fragmentTransaction.commit();
我认为您可以在 list_fragment2
中创建 list_fragment2
代码实例。也许您的代码重新创建了 list_fragment2 多次。
public static list_fragment2 createInstance() {
list_fragment2 fragment = new list_fragment2();
Bundle bundle = new Bundle();
bundle .putString("test","text");
fragment.setArguments(bundle);
return fragment;
}
我正在使用 Bundle 从我的第一个 TabFragment
传递数据,但它提示 NullPointerException
。当 getArguments()
in list_fragments2
in second tab
MainActivity 片段
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
Toast.makeText(this, "" + b, Toast.LENGTH_SHORT).show();
SecondActivity 片段
public class list_fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View h = inflater.inflate(R.layout.tab2, container, false);
TextView textView = (TextView) h.findViewById(R.id.textView);
Bundle bundle=getArguments();
//your string
if(bundle != null) {
String test = bundle.getString("test");
textView.setText(test);
}
return h;
}
}
你真的加载了你的第二个片段吗?
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
fragmentTransaction.replace(placeholder, fragment);
fragmentTransaction.commit();
我认为您可以在 list_fragment2
中创建 list_fragment2
代码实例。也许您的代码重新创建了 list_fragment2 多次。
public static list_fragment2 createInstance() {
list_fragment2 fragment = new list_fragment2();
Bundle bundle = new Bundle();
bundle .putString("test","text");
fragment.setArguments(bundle);
return fragment;
}