无法在嵌套片段中更改ActionBar标题

时间:2016-03-20 18:47:39

标签: java android android-fragments android-viewpager

有一个片段,它的xml标记包含ViewPager。在此片段中,必须通过滑动在其他片段中实现导航。

public class MainFragment extends Fragment {

    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_fragment, null);

        ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        return view;
    }

    public class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0:
                    fragment = new Fragment1();
                    break;
                case 1:
                    fragment = new Fragment2();
                    break;
            }
            return fragment;
        }
    }
}

一切都运作良好。问题是Fragment1无法使用setTitle()方法设置自己的标题:标题保持不变

public class Fragment1 extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment1, null);

        getActivity().setTitle("Fragment 1");

        return view;
    }
}

出现问题的原因,以及为什么当我致电MainFragment时,包含setTitle()的父级动作的标题不会改变?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容更新片段中的活动标题:

((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("My custom title");