1

I am having issues setting the title of my toolbar, which only seems to work when there is a delay.

For example a simple oncreate() method for my app 'Forecast'

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    setSupportActionBar(_toolbar);
    setTitle("ABCDEFG");
}

When the app is run, the toolbar has the name of my app, not 'ABCDEFG'.

However, if I put a 200 millisecond delay before setting the title..

    Observable.just("ABCDEFG")
            .delay(200,TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(this::setTitle);

My Toolbar title is correctly displayed as "ABCDEFG"

this is the same when it comes to doing anything with the Toolbar, does anyone know what is actually going on here? and how I can solve this without having to put a delay in?

Here is my toolbar xml..

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">


    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        app:layout_collapseMode="pin"
        app:layout_scrollFlags="scroll"
        app:popupTheme="@style/AppTheme.PopupOverlay" />


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

Thanks for your help!

EDIT forgot to mention setTitle() simply calls _toolbar.setTitle(title)

Tmarsh2
  • 417
  • 2
  • 16

2 Answers2

2

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

Rahim Khalid
  • 469
  • 6
  • 15
0

As maRShmallow stated, I changed _toolbar.setTitle() to getSupportActionBar().setTitle()

Tmarsh2
  • 417
  • 2
  • 16