Reputation: 3772
I'm extending AppCompatActivity
and setting ActionBar
using setSupportActionBar()
.
There's a bit of confusion in setting the title.
If I do -
Toolbar toolbar = (Toolbar) findViewById(R.id.titlebar);
setSupportActionBar(toolbar);
toolbar.setTitle("Title 1"); // Does not work
setTitle("Title 2"); // Works
getSupportActionBar().setTitle("Title 3"); // Works
setTitle("Title 4"); // Does not work. Why?
What I see is that getSupportActionBar().setTitle()
is creating a new view for the title and then the activity is losing the reference to it.
Is this the intended behavior or a bug in Android?
Upvotes: 2
Views: 202
Reputation: 524
copy this line
setSupportActionBar(toolbar);
add the end of your line.
Toolbar toolbar = (Toolbar) findViewById(R.id.titlebar);
setSupportActionBar(toolbar);
toolbar.setTitle("Title 1");
setTitle("Title 2");
getSupportActionBar().setTitle("Title 3");
setTitle("Title 4");
setSupportActionBar(toolbar);
Upvotes: 1
Reputation: 1701
It's an intended behaviour once your set setSupportActionBar(Toolbar)
. support library internal creates new view for display title.
setTitle()
is method of Activity
it'll update only title if used setActionBar(Toolbar)
. But, it doesn't have backward compatability.
Ref
Upvotes: 0
Reputation: 357
If you call setSupportActionBar(Toolbar),
then the Action Bar is then responsible for handling the title, therefore you need to call getSupportActionBar().setTitle("My Title");
to set a custom title.
Also check this link where toolbar.setTitle("My title");
may cause problem like below:- In android app Toolbar.setTitle
method has no effect – application name is shown as title
And toolbar
is the general form of action bar.
We can have multiple toolbars as layout widget but action is not.
Thus better approach is to use getSupportActionBar().setTitle("My Title");
Upvotes: 1