当 View 的主要部分发生某些事情时,我试图动态更改自定义 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");
关于android - 如何动态更改自定义ActionBar标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758887/