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

时间:2016-09-28 22:57:37

标签: android android-layout android-actionbar android-linearlayout custom-titlebar

当我在视图的主要部分发生某些事情时,我试图动态更改自定义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>

1 个答案:

答案 0 :(得分:2)

TextView一个ID:

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

在自定义findViewById()上致电View以获取它:

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

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

title.setText("New title");
相关问题