Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getSupportActionBar().setTitle() vs toolbar.setTitle()

Tags:

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?

like image 510
Farbod Salamat-Zadeh Avatar asked Dec 06 '15 13:12

Farbod Salamat-Zadeh


People also ask

What is Toolbar Android?

In Android applications, Toolbar is a kind of ViewGroup that can be placed in the XML layouts of an activity. It was introduced by the Google Android team during the release of Android Lollipop(API 21). The Toolbar is basically the advanced successor of the ActionBar.

How do I change the title text bar in Android?

First, add a font file in the src/main/assets/fonts/ of your project. Then create variables for Toolbar and text title and call the method findViewById(). Create a new Typeface from the specified font data. And at last setTypeface in text title.


1 Answers

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

like image 127
Androider Avatar answered Oct 14 '22 04:10

Androider