How to dynamically change a custom ActionBar title?

1.5k Views Asked by At

I'm trying to change a custom ActionBar title dynamically, when certain things happen in the main part of the view. And even though I've been able to initially set the title correctly, using the following code ...

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.activity_scanning_title);

I cannot seem to get access to the right object from the ActionBar in order to modify it when needed. Because the intuitive option was getCustomView(), I've gotten as far as:

ActionBar bar = getSupportActionBar();
android.view.View v = bar.getCustomView();
if (v instanceof android.widget.LinearLayout)
{
     LinearLayout layt = (LinearLayout)v;
     // ???
     . . .
}

and it turns that getCustomView() indeed returns a LinearLayout, but I cannot get at the TextView that is part of the layout, which properly displayed the original title, only I need to change it.

The xml for the LinearLayout that defines my custom title is here:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Scan Assessment"
    android:textColor="#ffffff"
    android:textSize="18sp" />
</LinearLayout>
1

There are 1 best solutions below

1
Mike M. On BEST ANSWER

Give the TextView an ID:

<TextView
    android:id="@+id/title"
    ... />

Call findViewById() on the custom View to get it:

TextView title = (TextView) bar.getCustomView().findViewById(R.id.title);

And use the setText() method to change your title:

title.setText("New title");