获取动作条标题的TextView与AppCompat V7 R21动作、标题、TextView、AppCompat

2023-09-05 06:55:52 作者:九條狗友i

我有需要使用的TextView的颜色的动作条的标题库。在此之前AppCompat V7 R21我可以findViewById,并获得直接从视图中的颜色。然而,由于某种原因,现在不工作。该视图总是空。我已经写了code解析整个视图层次结构,并打印出编号,类型和值对所有TextViews。标题视图没有身份证,我觉得这很奇怪。

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.

有一件事我注意到的是,当我试图得到什么返回是一个工具栏(尽管我没有在我的应用程序使用一个工具栏)的动作条。所以我遍历工具栏的孩子们的意见,每当一个TextView发现我比较其文本值与toolbar.getTitle(),以确保这就是我要找的TextView的。不理想,我不知道这是否会适用于所有情况。

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?

推荐答案

在我的情况下,使用该工具栏通常当,如果我做一些自定义的标题,我只是手动充气标题视图,然后设置其属性的XML。工具栏的一点是prevent这样的事情发生,这样你就可以更好地控制你的工具栏看起来像

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>

然后在code,你会做这样的事情:

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

我知道这是一个老帖子,但这已经我已经找到了使在工具栏自定义textc颜色和字体的最佳方式

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