我正在使用Bundle从我的第一个TabFragment
传递数据,但它会提示NullPointerException
。第二个标签中的getArguments()
中的list_fragments2
MainActivity Fragment
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 Fragment
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;
}
}
答案 0 :(得分:1)
你真的加载了你的第二个片段吗?
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();
答案 1 :(得分:0)
我认为您可以在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;
}