Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

android - Getting ActionBar Title TextView with AppCompat v7 r21

I have a library that requires to use the color of the TextView for the ActionBar title. Prior to AppCompat v7 r21 I could just findViewById() and get the color from the view directly. However, for some reason now that does not work. The view is always null. I've written code that parses the entire view hierarchy and prints out the IDs, types and values for all TextViews. The title view had no ID, which I find very weird.

One thing I noticed was when I tried to get the ActionBar what was returned was a Toolbar (even though I didn't use a Toolbar in my app). So I iterated over the Toolbar's children views and whenever a TextView was found I compared its text value with the toolbar.getTitle() to make sure that's the TextView I'm looking for. Not ideal and I'm not sure if it'll work for all cases.

Does anyone know what could be the safest solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

I know this is an older post, but this has been the best way I have found for allowing custom textc color and fonts in the Toolbar


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...