0

I have my MainActivity and a few fragments, and I want to change the Toolbar title depending on the Fragment displayed.

I have tried using getActivity().setTitle(R.string.buscar_futbolista); in onCreateView of the Fragment, but is not changing the title. Why?

In my MainActivity, in onCreate method I have the following:

Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(R.string.inicio);
setSupportActionBar(toolbar);

Thank you in advance!

xerez
  • 35
  • 5

2 Answers2

1

This solution worked for me: https://stackoverflow.com/a/26998718/21021740

I replaced getActivity().setTitle(R.string.buscar_futbolista); by ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.buscar_futbolista);.

xerez
  • 35
  • 5
  • Because you are in a Fragment, getActivity() will alway return FragmentActivity, for setTitle to work you need AppCompatActivity – Samsad CV Apr 13 '23 at 05:14
0

In code you have mentioned, you're trying to do two things at once that is setting actionbar title and toolbar title. That is why its not working.

Solution:

If you want to set title to your Actionbar this is how you can do it:

 ActionBar actionBar = getSupportActionBar();
 actionBar.setTitle("ACTIONBAR TITLE");

Now if you want to set title to Custom toolbar that you have created you can do it like this:

Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("TOOLBAR TITLE");

Remember:

ActionBar is the element present at the top of the activity screen. It is a salient feature of a mobile application that has a consistent presence over all its activities.

Toolbar is a View included in a layout like any other View. As a regular View , the toolbar is easier to position, animate and control. Multiple distinct Toolbar elements can be defined within a single activity.

Let me know if it you any doubts. Happy Coding!!

  • Hi @Shivrajsinh Sarvaiya, thank you for your explanaiton, but I am using a `NoActionBar` theme (in `themes.xml` I have ` – xerez Apr 05 '23 at 10:38