以编程方式更改 AppBarLayout 主题?
Change AppBarLayout theme programmatically?
我有一个这样定义的 AppBarLayout
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
然而,有时我会更改应用程序的主题,我也想更改它,以及它的 children。通过这样做,我取得了部分成功:
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
appBarLayout.getContext().setTheme(R.style.AppTheme_Dark_AppBarOverlay);
appBarLayout.invalidate();
但是,标题的 TextView 没有获取主题设置。
如何设置?
来自documentation for Context.setTheme():
Set the base theme for this context. Note that this should be called
before any views are instantiated in the Context (for example before
calling setContentView(View) or inflate(int, ViewGroup)).
最重要的是,在 Context
上设置主题会影响以后创建的视图。这意味着您必须在 setTheme()
.
之后重建您的布局
解决这个问题的方法是使用一个 ViewStub (http://developer.android.com/reference/android/view/ViewStub.html),它包含我的 AppBarLayout 的两个版本:Light 和 Dark。
然后在 onCreate
中,我检查了正在加载的主题并将 ViewStub 替换为正确的 R.layout
。不知道为什么这么难,也不知道为什么整个Activity改主题的时候,子视图的'theme'却改不了,真是百思不得其解。
无论如何,这是唯一对我有用的解决方案。
我有一个这样定义的 AppBarLayout
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
然而,有时我会更改应用程序的主题,我也想更改它,以及它的 children。通过这样做,我取得了部分成功:
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
appBarLayout.getContext().setTheme(R.style.AppTheme_Dark_AppBarOverlay);
appBarLayout.invalidate();
但是,标题的 TextView 没有获取主题设置。
如何设置?
来自documentation for Context.setTheme():
Set the base theme for this context. Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).
最重要的是,在 Context
上设置主题会影响以后创建的视图。这意味着您必须在 setTheme()
.
解决这个问题的方法是使用一个 ViewStub (http://developer.android.com/reference/android/view/ViewStub.html),它包含我的 AppBarLayout 的两个版本:Light 和 Dark。
然后在 onCreate
中,我检查了正在加载的主题并将 ViewStub 替换为正确的 R.layout
。不知道为什么这么难,也不知道为什么整个Activity改主题的时候,子视图的'theme'却改不了,真是百思不得其解。
无论如何,这是唯一对我有用的解决方案。