片段中的工具栏不显示其标题

时间:2017-07-25 12:43:32

标签: android fragment title

我的活动风格是" Theme.AppCompat.Light.NoActionBar"。 片段中有一个工具栏,稍后会添加到我的活动中。

我无法设置操作栏的标题。下面的代码不起作用。请帮我。如何在片段中设置工具栏的标题?

//In the fragment
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
        Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        int i = getArguments().getInt(ARG_SECTION_NUMBER);
        toolbar.setTitle("aaa");
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);

        CharSequence title = ((AppCompatActivity) getActivity()).getSupportActionBar().getTitle();

        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

3 个答案:

答案 0 :(得分:0)

尝试在活动中添加ViewPager.addOnPageChangeListener并根据您的片段更改设置操作栏标题尝试此操作确保对您有所帮助

        ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if(position==0){
                getSupportActionBar().setTitle("Nilesh Rathod");

                // or try this
                Toolbar actionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);            
                actionBarToolbar.setTitle("NILESH");
                setSupportActionBar(actionBarToolbar);


            }else if(position==1){
                getSupportActionBar().setTitle("Prem Rathod");
                // or try this
                Toolbar actionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);            
                actionBarToolbar.setTitle("PREM");
                setSupportActionBar(actionBarToolbar);

            }
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

答案 1 :(得分:0)

试试这个

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main2, container, false);
        Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        int i = getArguments().getInt(ARG_SECTION_NUMBER);

        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);



        CharSequence title = ((AppCompatActivity) getActivity()).getSupportActionBar().getTitle();

        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

答案 2 :(得分:0)

  

即使有   setHasOptionsMenu(false);所以你必须做一个真正的菜单并填充   在您在片段的onCreateView中创建的工具栏中

toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
    toolbar.inflateMenu(R.menu."Menu u created");
    Menu menu = toolbar.getMenu();
    toolbar.setTitle("");
    toolbar.setSubtitle("");