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
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");