繁体   English   中英

如何动态更改自定义 ActionBar 标题?

[英]How to dynamically change a custom ActionBar title?

当视图的主要部分发生某些事情时,我正在尝试动态更改自定义 ActionBar 标题。 即使我已经能够最初正确设置标题,使用以下代码......

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

我似乎无法从 ActionBar 访问正确的对象,以便在需要时对其进行修改。 因为直观的选项是 getCustomView(),所以我得到了:

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

结果发现 getCustomView() 确实返回了一个 LinearLayout,但是我无法获得作为布局一部分的 TextView,它正确地显示了原始标题,只有我需要更改它。

定义我的自定义标题的 LinearLayout 的 xml 在这里:

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

TextView一个 ID:

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

在自定义View上调用findViewById()以获取它:

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

并使用setText()方法更改您的标题:

title.setText("New title");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM