首先,我通过XML设置AppBarLayout主题:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/MyTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/MyTheme.PopupOverlay"
app:titleTextAppearance="@style/MyTheme.Toolbar.Title" />
其中@style/MyTheme.AppBarOverlay包含:
<style name="MyTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="colorPrimary">@drawable/toolbar_background</item>
</style>
但是在某些情况下,我想通过编程方式更改它,而不更改活动的主题(仅更改AppBarLayout的主题)。
我尝试了这两种方法,但没有成功:
第一步:
ActionBar actionBar = getSupportActionBar(); actionBar.getThemedContext().setTheme(R.style.MyTheme_AppBarOverlay_2);
第二步:
AppBarLayout mAppBar = (AppBarLayout) findViewById(R.id.appbar); mAppBar.getContext().setTheme(R.style.MyTheme_AppBarOverlay_2);