通过在选项卡布局之间使用bundle传递数据



我正在使用 Bundle 从我的第一个TabFragment传递数据,但它会提示NullPointerException.在第二个选项卡中getArguments() list_fragments2时出错

主活动片段

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

第二个活动片段

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

最新更新