Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get action bar title as TextView in AppCompat?

Tags:

android

I'm trying this to get title as TextView but it's not working:

TextView title = (TextView) findViewById(R.id.action_bar_title);

And title is null. How to get title as TextView using AppCompat?

like image 973
krystian71115 Avatar asked Dec 20 '22 02:12

krystian71115


1 Answers

Typically when using the Toolbar in my cases, if I am doing something custom with the title, I will just inflate the title view manually, then set its attributes in XML. The point of Toolbar is to prevent things like this from happening, so you can have more control over what your toolbar looks like

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_awesome_toolbar"
    android:layout_height="@dimen/standard_vertical_increment"
    android:layout_width="match_parent"
    android:minHeight="@dimen/standard_vertical_increment"
    android:background="@drawable/actionbar_background">


    <TextView
        style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/Red" />

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

Then in code, you would do something like this:

Toolbar toolbar = findViewById(R.id.my_awesome_toolbar);
//Get rid of the title drawn by the toolbar automatically
toolbar.setTitle("");
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setTextColor(Color.BLUE);

Taken from Getting ActionBar Title TextView with AppCompat v7 r21

like image 122
Shekhar Avatar answered Jan 31 '23 09:01

Shekhar