通过在tablayout之间使用bundle传递数据

时间:2017-01-03 03:35:14

标签: android android-fragments nullpointerexception fragment-tab-host

我正在使用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;

    }
}

2 个答案:

答案 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;
    }