Adding two AppCompat Toolbars with different theme

2019-02-23 00:18发布

问题:

I would like to have two different android.support.v7.widget.Toolbars in my app, one dark, one light, and switch between them when needed. However, when I set a different theme on the second toolbar, it seems to reset the theme on the first toolbar as well.

Is that a bug or intended behavior?

Toolbar 1:

<android.support.v7.widget.Toolbar
xmlns:sothree="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_gravity="top"
android:background="@drawable/action_bar_background"
sothree:theme="@style/ThemeOverlay.AppCompat.ActionBar"
sothree:contentInsetStart="0dp"/>

Toolbar 2:

<android.support.v7.widget.Toolbar
xmlns:sothree="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/clip_toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_gravity="top"
android:background="@android:color/transparent"
sothree:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
sothree:popupTheme="@style/ThemeOverlay.AppCompat.Light"
sothree:contentInsetStart="0dp"/>

回答1:

Make a ContextThemeWrapper:

ContextThemeWrapper wrapper = new ContextThemeWrapper(context, R.style.Some_Theme);

Use the current Context to inflate one toolbar and use the ContextThemeWrapper to inflate the other. Use getLayoutInflater() to get the inflater for each context.