In android app Toolbar.setTitle method has no effect – application name is shown as title
Asked Answered
C

27

337

I'm trying to create simple application using android-support-v7:21 library.

Code snippets:
MainActivity.java

public class MainActivity extends ActionBarActivity {

    Toolbar mActionBarToolbar;

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

        mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);            
        mActionBarToolbar.setTitle("My title");
        setSupportActionBar(mActionBarToolbar);
}

activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar            
        android:id="@+id/toolbar_actionbar"
        android:background="@null"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:fitsSystemWindows="true" />

</LinearLayout>

But instead of "My title" on Toolbar %application name% is shown.
Seems like setTitle method has no effect.
I would like to show "My title".

UPD: Before, styles.xml was:

<style name="AppTheme" parent="Theme.AppCompat">
    <item name="windowActionBar">false</item>
</style>

So, I thought that actionbar is not used. I add NoActionBar to style parent:

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="windowActionBar">false</item>
</style>

But the problem is not resolved.

Cobaltous answered 21/10, 2014 at 12:27 Comment(3)
FWIW, I'm on api level 22, and I had the same issue if calling setTitle after calling setSupportActionBar, but it worked if calling setTitle before. As described in an answer below, after calling setSupportActionBar, the action bar takes ownership of the toolbar and calls directly on the toolbar might not work. I do realize that in your question you did in fact call setTitle before setSupportActionBar, so probably this is something that has changed recently. In any case, using getSupportActionBar().setTitle works just as well.Coverdale
The same query asked in #15561404Flatt
Try it - “How set a title for Activity with ToolBar?” link.medium.com/cGVg3zVr0ZAgainst
C
611

Found the solution:

Instead of:

mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);            
mActionBarToolbar.setTitle("My title");
setSupportActionBar(mActionBarToolbar);

I used:

mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);            
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle("My title");

And it works.

Cobaltous answered 22/10, 2014 at 11:53 Comment(9)
nice one, but makes no sense to work this way and not the other....welcome to android 101Cortie
getSupportActionBar().setTitle("My title"); may produce 'java.lang.NullPointerException'Hurlow
@PratikButani So long as the Toolbar has been set as setSupportActionBar() before calling getSupportActionBar() why might it?Elsyelton
AndroidStudio giving warning if u use Inspect Code.Hurlow
Aha, easily resolved: assert getSupportActionBar() != null;Elsyelton
For me the first snippet you pasted works but the second doesn't!Ibnsaud
Would you please explain why?Helenahelene
Guys did you really upvoted @PratikButani comment so many times? If you use style theme without action bar but custom support toolbar v7 and you forget to call setSupportActionBar(mToolbar) of course you will get null exeption, but if you called it then just ignore this message. Just read - developer.android.com/training/appbar/setting-up.htmlJerrilyn
Setting the title before setSupportActionBar now works for me. @Jerrilyn agree!Flirtatious
G
126

For anyone who needs to set up the title through the Toolbar some time after setting the SupportActionBar, read this.

The internal implementation of the support library just checks if the Toolbar has a title (not null) at the moment the SupportActionBar is set up. If there is, then this title will be used instead of the window title. You can then set a dummy title while you load the real title.

mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("");
setSupportActionBar(mActionBarToolbar);

later...

mActionBarToolbar.setTitle(title);
Guardrail answered 16/2, 2016 at 10:53 Comment(6)
It works, but why this is the way it must be done makes no sense to me. Does anyone have an explanation for why this works?Ache
@Ache It makes sense considering the design of the actionbar/toolbar interaction. The Activity should display a title, if you provide a toolbar without that title, android assumes you want the traditional Activity title control.Culver
mActionBarToolbar.setTitle(getResources().getString(R.string.app_name)); will ensure there is a good default title while keeping the same magical effect of the answerHorsefaced
@Bevor it works, just see how many votes this answer has... you just did something wrongJerrilyn
@user25, it also worked bad for me, it removed a back arrow. Then I found another solution: https://mcmap.net/q/98163/-in-android-app-toolbar-settitle-method-has-no-effect-application-name-is-shown-as-title. this.setTitle("Title"), where this - is a reference to an activity.Coker
i enhanced this answer for those using a collapsing toolbar: #26487230Verbosity
H
90

The above answer is totally true but not working for me.

I solved my problem with the following things.

Actually My XML is like that:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/confirm_order_mail_layout"
    android:layout_width="match_parent"
    android:layout_height="fill_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/confirm_order_appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/confirm_order_list_collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|enterAlways">

            <android.support.v7.widget.Toolbar
                android:id="@+id/confirm_order_toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

I have tried all the option and after all I just removed CollapsingToolbarLayout because of i do not need to use in that particular XML So My Final XML is like:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/confirm_order_mail_layout"
    android:layout_width="match_parent"
    android:layout_height="fill_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/confirm_order_appbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/confirm_order_toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

Now you have to use setTitle() like above answer:

mActionBarToolbar = (Toolbar) findViewById(R.id.confirm_order_toolbar_layout);            
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle("My Title");

Now If you want to use CollapsingToolbarLayout and Toolbar together then you have to use setTitle() of CollapsingToolbarLayout

CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.confirm_order_mail_layout);
collapsingToolbarLayout.setTitle("My Title");

May it will helps you. Thank you.

Hurlow answered 15/9, 2015 at 9:43 Comment(7)
That makes sense, removing the CollapsingToolbarLayout solved the problemParagraph
For me the trick with setting title for CollapsingToolbarLayout works. Thanks a lot!Arterial
Can I change the subtitle with CollapsingToolbarLayout?Dianndianna
Since you toolbar is nested under CollapsingToolbarLayout then it is overridden by collapsing toolbar layout. This works for me.Geraint
Bro you save my life!!! You must both setSupportActionbar before you use collapsingToolbarLayout.seTitle("Title");Microseism
... collapsingToolbarLayout.setTitle("My Title"); worket for me perfectly without to remove the collapsingToolbarLayoutWarhorse
Helped me a lot... ThanksMalefactor
R
46

Simply you can change any activity name by using

Activityname.this.setTitle("Title Name");
Revolution answered 13/11, 2016 at 6:46 Comment(1)
Or simply title = "Title" in Kotlin or maybe this.setTitle("Title") in Java.Coker
P
35

Try this, you can define title directly in XML:

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:title="some title"
        app:popupTheme="@style/AppTheme.PopupOverlay">
Petition answered 1/5, 2016 at 7:1 Comment(1)
The easiest but still i need to custom titles dynamically, if you have any ideaMinier
R
15

To set the title for each Navbar fragment title

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    myView = inflater.inflate(R.layout.second_layout, container, false);
    getActivity().setTitle("title");

    return myView;
}
Revolution answered 1/8, 2016 at 12:8 Comment(0)
C
12

Try this .. this method works for me..!! hope it may help somebody..!!

<android.support.v7.widget.Toolbar  
 xmlns:app="http://schemas.android.com/apk/res-auto"  
 android:id="@+id/my_awesome_toolbar"  
 android:layout_width="match_parent"  
 android:layout_height="wrap_content"  
 android:background="?attr/colorPrimary"  
 android:minHeight="?attr/actionBarSize"  
 app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >  

<TextView  
   android:id="@+id/toolbar_title"  
   android:layout_width="wrap_content"  
   android:layout_height="wrap_content"  
   android:gravity="center"  
   android:singleLine="true"  
   android:text="Toolbar Title"  
   android:textColor="@android:color/white"  
   android:textSize="18sp"  
   android:textStyle="bold" />  

</android.support.v7.widget.Toolbar>  

To display logo in toolbar try the below snippet. // Set drawable

toolbar.setLogo(ContextCompat.getDrawable(context, R.drawable.logo));

Let me know the result.

Connate answered 4/11, 2015 at 20:34 Comment(2)
Thank you Ragu Swaminathan.. I was trying to implement SupportActionBar from appcompact activity to give a title to my activity but unable to do it beacuse i need to extend BaseGameActivity. Then i go for toolbar but title not displayed while running. Your method using textbox inside toolbar is working. Recommend it to people in same situationTend
toolbar has a method to set the app logo. check my updated answerConnate
A
11
 getSupportActionBar().setTitle("Your Title");
Allograph answered 23/6, 2018 at 12:10 Comment(2)
This answer is a stub and should rather be a comment, since short answers like this may be considered low quality. Once you have sufficient reputation you will be able to comment. If you don't have enough reputation, read this post on how to contribute if you don't have enough reputation yet.Panettone
@Panettone it is an answerAlbescent
T
8

Please see https://code.google.com/p/android/issues/detail?id=77763. Apparently it is supposed to work like that. Once you call the setSupportActionBar() method call, it then is the responsibility of the ActionBar delegate to route the call to the correct view.

Tumblebug answered 5/1, 2015 at 8:1 Comment(1)
What's that Actionbar delegate? Here setTitle() doesn't work for toolbar neither for the support actionbar. The native actionbar is disabled in the theme. What the hell is wrong? If only the source code attachment worked in Android Studio I could trace the problem myself!Chaldea
J
7

It's not just about .setTitle

more methods of Support Toolbar (Appcompat v7) in onCreate works only with

getSupportActionBar().method()

and don't work with mToolbar.method()

examples:

getSupportActionBar().setTitle("toolbar title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

though next methods works fine without getSupportActionBar() in onCreate

mToolbar.setVisibility(View.VISIBLE);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //
    }

Problem only with onCreate event, you still can use mToolbar.setTitle() later instead of annoying getSupportActionBar().setTitle(), for example if you add this in onCreate it will work (because it will be executed later, after onCreate)

mHandler.post(new Runnable() {
    @Override
    public void run() {
        mToolbar.setTitle("toolbar title");
    }
});

I prefer to use this solution https://mcmap.net/q/98163/-in-android-app-toolbar-settitle-method-has-no-effect-application-name-is-shown-as-title than https://mcmap.net/q/98163/-in-android-app-toolbar-settitle-method-has-no-effect-application-name-is-shown-as-title because if you change title many times (in different functions) it's more comfortable to use mToolbar.setTitle() than longer getSupportActionBar().setTitle() one and you don't see annoying notification about null exception like with getSupportActionBar().setTitle()

Jerrilyn answered 20/3, 2018 at 12:15 Comment(1)
if you want to change the title many times and and using a collapsing toolbar, this will help: #26487230Verbosity
V
7

For anyone who needs to set up the title through the Toolbar some time after setting the SupportActionBar (@sorianiv) AND your Toolbar is inside a CollapsingToolbarLayout, read this:

mToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
//toolbar.setTitle(""); // no need to do this
//mToolbarLayout.setTitle("Title"); // if you need an initial title, do this instead
setSupportActionBar(toolbar);

Then later,

mToolbarLayout.setTitle("New Title");
Verbosity answered 24/8, 2019 at 6:41 Comment(0)
P
6

I tried to rename the toolbar from the fragment

It helped me, I hope to help someone else

Activity activity = this.getActivity();
Toolbar toolbar = (Toolbar) activity.findViewById(R.id.detail_toolbar);
        if (toolbar != null) {
            activity.setTitle("Title");
        }

//toolbar.setTitle("Title"); did not give the same results

Screenshot: enter image description here

Pooh answered 30/1, 2016 at 4:47 Comment(0)
N
5

Application title will not show as default title on every activity, you can insert different title on every activity. On your activity file bellow the onCreate just paste a single line to set title,

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("Your Title Here");

Just change the text "Your Title Here" to your text.

Nidifugous answered 24/9, 2019 at 12:22 Comment(0)
S
4

Simply use this in your adapter, Where MainActivity is your AppCompactActivity. Call it from anywhere.

((MainActivity) context).getSupportActionBar().setTitle(titles.get(position));
Sclar answered 14/4, 2016 at 5:31 Comment(0)
J
4

I made it work by using -

toolbar.post(new Runnable() {
            @Override
            public void run() {
                toolbar.setTitle("My Title");
            }
        });
Judaea answered 1/2, 2017 at 16:7 Comment(1)
You don't need to use post if you're changing title in UI thread, which I think is 90% of cases.Oviposit
C
4

If you are using CollapsibleToolbarLayout along with Toolbar then you will need to set title in both the layouts

set your Toolbar as action bar in onCreate method

protected void setUpToolBar() {

    if (mToolbar != null) {
        ((HomeActivity) getActivity()).setSupportActionBar(mToolbar);
        mToolbar.setTitleTextColor(Color.WHITE);
        mToolbar.setTitle("List Detail");
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity()
                        .getSupportFragmentManager().popBackStack();
            }
        });
        ((HomeActivity) getActivity()).getSupportActionBar()
                .setDisplayHomeAsUpEnabled(true);
    }
}

Later simply update title of toolbar using setTitle method

 mToolbar .setTitle(productFromShoppingList.getProductName()); 
 mCollapsingToolbar.setTitle(productFromShoppingList.getProductName());
Claiborn answered 8/9, 2017 at 13:58 Comment(2)
This solution works if you're finding that you can set the title once, but can't change it after that. Make sure you're setting the title of the Collapsing Toolbar.Stanislaw
if you want to change the title after some time with collapsing toolbar, you can do this: #26487230Verbosity
A
3

I have a strange behaviour that may can help you.
This is working but it has no effect in onCreate only:

toolbar.setTitle("title");

Try to use this in onCreate:

yourActivityName.this.setTitle("title")
Averment answered 1/2, 2018 at 4:51 Comment(0)
E
3

This can be done by setting the android:label attribute of your activity in the AndroidManifest.xml file:

<activity android:name="my activity"
 android:label="The Title I'd like to display" />

And then add this line to the onCreate():

getSupportActionBar().setDisplayShowTitleEnabled(true);
Ethanethane answered 18/3, 2018 at 6:54 Comment(0)
R
2

To change the title for each different activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pizza);
    setTitle(getResources().getText(R.string.title));
}
Revolution answered 1/8, 2016 at 12:0 Comment(1)
setTitle(R.string.title); Event easier, but doesn't workCassy
S
2

Try this:

Xml Code

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:id="@+id/tool_bar"
    android:background="@color/tablayout"
    android:theme="@style/ToolBarStyle"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:layout_gravity="center"
        android:id="@+id/toolbar_title"
        android:textSize="18sp"
        android:textColor="@color/white"/>
    </android.support.v7.widget.Toolbar>

Java Code

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    toolbar_text = (TextView)findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    toolbar.setLogo(R.drawable.ic_toolbar);
}
Steerageway answered 1/8, 2016 at 12:23 Comment(0)
W
2

If your goal is to set a static string in the toolbar, the easiest way to do it is to simply set the activity label in AndroidManifest.xml:

<activity android:name=".xxxxActivity"
          android:label="@string/string_id" />

The toolbar will get this string without any code. (works for me with v27 libraries.)

While answered 19/2, 2018 at 17:20 Comment(0)
G
2
 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       //custom toolbaar
       getSupportActionBar().setTitle("Abhijeet");

    }
}
Gnarl answered 29/2, 2020 at 6:23 Comment(0)
A
1

Though not immediately relevant to this particular setup, I found that removing "CollapsingToolbarLayout" from my XML that was wrapping my toolbar inside of an AppBarLayout made everything work.

So, this:

      <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways"
                app:navigationIcon="@drawable/ic_arrow_back_white_24dp" />

        </android.support.design.widget.AppBarLayout>

Instead of this:

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/collapsingToolbar"
                android:minHeight="?attr/actionBarSize"
                app:layout_scrollFlags="enterAlways|scroll|snap">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_height="?attr/actionBarSize"
                    app:navigationIcon="@drawable/ic_arrow_back_white_24dp" />
            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

Then, I set the title in the activity's onCreate, before setSupportActionBar() is called.

Aurify answered 11/10, 2017 at 18:11 Comment(2)
you could do that. if you really need the collapsing toolbar layout, check this: #26487230Verbosity
@Chantell Osejo this worked for me too, even I was using the same layout. ThanksEcklund
M
0

Make sure you add this option:

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
Mcdowell answered 27/1, 2017 at 0:58 Comment(0)
B
0

The answer is in the documentation (which you can find here):

To use the ActionBar utility methods, call the activity's getSupportActionBar() method. This method returns a reference to an appcompat ActionBar object. Once you have that reference, you can call any of the ActionBar methods to adjust the app bar. For example, to hide the app bar, call ActionBar.hide().

That is the solution you actually found. Just thought of giving a reference to the official documentation (which apparently few tend to read).

Babb answered 5/5, 2018 at 18:7 Comment(0)
E
0

In Kotlin you can do this:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar

class SettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)

        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setTitle(R.string.title)

    }

    override fun onSupportNavigateUp() = true.also { onBackPressed() }

}
Ertha answered 20/1, 2020 at 12:13 Comment(0)
M
-2

This is happening because you are using Toolbar and ActionBar both. Now as you want to use Toolbar as an action bar, the first thing you need to do is disable the decor provided action bar.

The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar.

Morice answered 21/10, 2014 at 12:34 Comment(4)
Sorry i misunderstood question.Shirleneshirley
@HareshChhelana You posted answer but do you know what is the issue exactly?Morice
I think which is related action bar set tile issue that y i given such ans and when you realize me this i deleted my ans so now you dont worried about my misunderstood brother.Shirleneshirley
@PareshMayani thank you for your answer, but it doesn't resolve my problem. Please, check updated questionCobaltous

© 2022 - 2024 — McMap. All rights reserved.