[英]How to change action bar title color in code
我無法以編程方式為 v11 及更高版本更改 androids 操作欄標題顏色。 我可以在 xml 中完成它,但需要在代碼中動態更改它。 我應該怎么做? 提前致謝。
ActionBar
標題 ID 是隱藏的,或者換句話說,它是內部的,通常無法訪問它。 您可以使用Resources.getIdentifier
然后使用View.findViewById
來引用它。
獲取 action_bar_title 的 ID
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
現在您可以將 ID 與TextView
TextView abTitle = (TextView) findViewById(titleId);
abTitle.setTextColor(colorId);
您可以使用 SpannableString 和 ForegroundColorSpan 來設置標題的顏色
Spannable text = new SpannableString(actionBar.getTitle());
text.setSpan(new ForegroundColorSpan(Color.BLUE), 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
actionBar.setTitle(text);
另一種方法是使用 Html
getSupportActionBar().setTitle((Html.fromHtml("<font color=\"#FF4444\">" + getString(R.string.some_string) + "</font>")));
如果使用v7 appcompat 庫(使用 r22 測試),那么您可以在Toolbar
對象上調用setTitleTextColor()
來替換所有 API 級別的操作欄。 例如:
Toolbar actionBarToolbar = (Toolbar)activity.findViewById(R.id.action_bar);
if (actionBarToolbar != null)
actionBarToolbar.setTitleTextColor(Color.RED);
如果您使用Sherlock Actionbar,您可以使用 sherlock-actionbar-id 來支持操作欄(Android 3.0 以下)
int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
if ( 0 == titleId )
titleId = com.actionbarsherlock.R.id.abs__action_bar_title;
使用 Kotlin 和 SupportActionBar 使用這個 ->
val mSpannableText = SpannableString(supportActionBar?.title)
mSpannableText.setSpan(
ForegroundColorSpan(Color.BLUE),
0,
mSpannableText.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
supportActionBar?.title = mSpannableText
要使自定義顏色起作用,您需要使用NoActionBar
例如android:Theme.NoTitleBar
或其android:Theme.NoTitleBar
之一,然后在您的布局中手動添加Toobar
,然后在您的活動的onCreate()
setSupportActionBar
,
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
然后你可以在工具欄 xml app:titleTextColor="@android:color/white"
設置標題顏色
見下文;
<androidx.appcompat.widget.Toolbar
app:navigationContentDescription="@string/abc_action_bar_up_description"
app:titleTextColor="@android:color/white"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:navigationIcon="?attr/homeAsUpIndicator"
app:title="@string/app_name"
android:minHeight="@dimen/abc_action_bar_default_height_material" />
至少這項工作是我的😊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.