【问题标题】:Change AppBarLayout theme programmatically?以编程方式更改 AppBarLayout 主题?
【发布时间】:2016-02-02 20:56:06
【问题描述】:

我有一个这样定义的 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">

但是,有时我会更改应用程序的主题,并且我也想更改它及其子主题。通过这样做,我取得了部分成功:

    AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
    appBarLayout.getContext().setTheme(R.style.AppTheme_Dark_AppBarOverlay);
    appBarLayout.invalidate();

但是,标题的 TextView 没有获取主题设置。

如何设置?

【问题讨论】:

    标签: android styles themes android-appbarlayout


    【解决方案1】:

    来自documentation for Context.setTheme()

    为此上下文设置基本主题。请注意,这应该被称为 在上下文中实例化任何视图之前(例如之前 调用 setContentView(View) 或 inflate(int, ViewGroup))。

    底线是在Context 上设置主题会影响以后创建的视图。这意味着您必须在 setTheme() 之后重建布局。

    【讨论】:

    • 是的,但我将它设置在 AppBarLayout 上,而不是整个应用程序上。我使用 getContext() 是因为 AppBarLayout 的上下文似乎与整体不同。如果我只需要重建它的一部分(我无法在我假设的视图构建之前得到它),我该怎么做
    • 您至少必须重建 AppBarLayout。您可以在基本上下文中使用 ContextThemeWrapper 以使用另一个主题重新膨胀视图。这样您的基本上下文就不会受到影响。
    • 没有其他方法可以在 AppBarLayout 上设置 android:theme 吗?这没有任何意义,如果您无法更改它们,为什么要在小部件上设置主题?
    • 很遗憾没有。视图在其构造函数中读取主题属性并相应地设置自己的样式。这会影响视图层次结构的所有子级。创作之后再定主题,就像是在炒鸡蛋一样。
    • 这很不幸,而且是 IMO 的一个相当糟糕的设计决定。我可以更改应用程序的主题,但不能更改视图? =\
    【解决方案2】:

    解决方案是使用一个 ViewStub (http://developer.android.com/reference/android/view/ViewStub.html),它包含两个版本的 AppBarLayout:Light 和 Dark。

    然后在onCreate 中,我检查了正在加载哪个主题,并将 ViewStub 替换为正确的R.layout。不知道为什么这么难,也不知道为什么在给整个Activity换主题的时候不能给子视图换‘主题’,真是让人费解。

    无论如何,这是唯一对我有用的解决方案。

    【讨论】:

      猜你喜欢
      • 2016-04-17
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      相关资源
      最近更新 更多