android - 如何在 AppCompat 中获取操作栏标题作为 TextView?

标签 android

我正在尝试将标题作为 TextView 获取,但它不起作用:

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

并且标题为空。如何使用 AppCompat 获取 TextView 的标题?

最佳答案

通常在我的案例中使用工具栏时,如果我对标题进行自定义操作,我将只手动扩充标题 View ,然后在 XML 中设置其属性。 Toolbar 的意义在于防止此类事情发生,因此您可以更好地控制工具栏的外观

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

然后在代码中,你会做这样的事情:

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

取自Getting ActionBar Title TextView with AppCompat v7 r21

关于android - 如何在 AppCompat 中获取操作栏标题作为 TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318818/

相关文章:

java - 实现加载/保存首选项集的 'profiles'?

android - 将背景图像从正常图像淡化为褪色图像

java - boolean onClickEventListener 返回的目的

android - Android 可以做点对点的 ad-hoc 网络吗?

java - 如果已知值,如何在 firebase 数据库中找到键?

java - Google Glass 的 Hello World 程序 - 一步一步

android - 关于 Android 中按钮的非常简单的示例?

Android微调器-奇怪的用户界面问题

Android android.view.InflateException 二进制 XML 文件行 #16 : Error inflating class fragment

android - 使用 Retrofit 发布正文 JSON