21

I am aware that there are two methods to setting a title in an Android Activity.

Assuming I already have the following code...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);

    ...

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(toolbar);

...I can use either this...

getSupportActionBar().setTitle("My title");

...or this...

toolbar.setTitle("My title");

...to set my title.

My question is, which is the better practice?

Farbod Salamat-Zadeh
  • 19,687
  • 20
  • 75
  • 125

2 Answers2

27

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

Community
  • 1
  • 1
Androider
  • 3,833
  • 2
  • 14
  • 24
  • 1
    Does this also mean that `getSupportActionBar().setHomeAsUpIndicator(int)` is better practice than `toolbar.setNavigationIcon(int)`, or are these slightly different? – Farbod Salamat-Zadeh Dec 11 '15 at 17:53
0
setSupportActionBar(toolbar);

The purpose of this line is to set the passed in toolbar as the activities app bar. So in this way either way is perfectly acceptable; personally as you have already created a toolbar, I would set the title of toolbar before passing it using the above method.

Eamon Scullion
  • 1,354
  • 7
  • 16