Set a title in Toolbar from fragment in Android

后端 未结 17 807
逝去的感伤
逝去的感伤 2021-01-31 03:40

I have been using the latest Toolbar from AppCompatv7 lib.I have placed a textview in the ToolBar ViewGroup And I want to set a title into this Textview from the fragment in my

17条回答
  •  别那么骄傲
    2021-01-31 04:17

    If somebody struggles with this problem, this may be useful.

    Basically you have 4 options, how to handle that:

    • use an interface in order to communicate with your activity, or any other convenient method, like an event bus.

    • you call getActivity().setTitle("Title"), but in this case you need to attach your Toolbar to the ActionBar by calling the setSupportActionBar() in your activity.

    • You can have a public instance of your Toolbar and access that instance from the fragment.

    • Finally, if you need the instance of your Toolbar(you may want to do something else with), you can simply get it this way:

      Toolbar bar=Toolbar.class.cast(getActivity().findViewById(R.id.toolbar));

    Well, the last option would solve the problem only if the Toolbar hasn't been passed to the setSupportActionBar method.

    If it has been, then you need to call this method in your activity:

    supportActionBar.setDisplayShowTitleEnabled(false),

    which will solve the problem.

    However, I would suggest to use ButterKnife which will make it a little bit cleaner, here an example:

      Toolbar actionBar=findById(getActivity(),R.id.actionBar);
      actionBar.setTitle("Title");
    

提交回复
热议问题