【问题标题】:Passing data by using bundle between tablayout在 tablayout 之间使用 bundle 传递数据
【发布时间】:2017-01-03 03:35:14
【问题描述】:

我正在使用 Bundle 从我的 First TabFragment 传递数据,但它以 NullPointerException 提示出来。当getArguments() 在第二个选项卡中的list_fragments2 时发生错误

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;

    }
}

【问题讨论】:

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


    【解决方案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();
    

    【讨论】:

    • 谢谢,我以前试过,但我仍然得到 nullpointerexception 这个错误
    • 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);捆绑包=getArguments(); //你的字符串 if(bundle != null) { String test = bundle.getString("test"); textView.setText(test); } 返回 h; } }
    • 请使用“更新”部分编辑您的原始帖子
    • list_fragment2 中找不到问题。您也可以发布您当前的Mainactivity 代码吗?请再次更新您的原始帖子。
    • 我还有更多问题吗?是否可以从 Mainactivity tablayout 使用捆绑传递数据到选项卡片段来做到这一点?
    【解决方案2】:

    我认为您可以在 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-25
      • 2017-01-18
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多