使用bundle返回null将值从一个片段传递到另一个片段

时间:2017-08-27 15:40:30

标签: android fragment bundle

我正在尝试使用Bundle从fragmentA到fragmentB同时传递两个值(Tablayout title和Spinner项)。但是fragmentB中的getArguments()返回null。

感谢您的帮助。

这是我的fragmentA的代码

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

            final int pos = tab.getPosition();

            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    year = spinner.getItemAtPosition(position).toString();
                    month = String.valueOf(mPagerAdapter.getPageTitle(pos).toString());
                    //Toast.makeText(getActivity().getBaseContext(), month + " " + year,Toast.LENGTH_SHORT).show();


                    FragmentB f = new FragmentB();

                    if(month != null && year != null) {
                        final Bundle b = new Bundle();
                        b.putString("m", month);
                        b.putString("y", year);
                        f.setArguments(b);
                    }



                }


                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });



        }

以下是fragmentB的代码

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);


    final Bundle bundle = getArguments();
    String month = "";
    String year = "";

    try
    {
        month = bundle.getString("m");
        year = bundle.getString("y");
        Toast.makeText(getActivity().getBaseContext(), month + " " + year, Toast.LENGTH_SHORT).show();
    }
    catch (final Exception e)
    {
        Toast.makeText(getActivity().getBaseContext(),"No data", Toast.LENGTH_SHORT).show();
    }

}

0 个答案:

没有答案