【问题标题】:How to choose my Theme in Android Studio layout preview如何在 Android Studio 布局预览中选择我的主题
【发布时间】:2019-03-13 18:34:11
【问题描述】:

在我项目的res/values 目录中,我有一个my_themes.xml 文件,它指定了自定义属性和两个自定义主题(浅色和深色)。这些主题通过the third constructor parameter 应用于(在代码中)Presentation 对象。

我希望在编辑布局文件时能够选择两个主题中的任何一个,并在布局预览中查看主题结果。当我运行代码时,一切正常;这只是一个关于如何让布局预览向我展示我的主题的问题。

但是,似乎无法选择我的自定义主题。当我单击下拉菜单选择要使用的主题时,只有我的“默认”AppTheme(及其父级)可见:

如果我点击“更多主题...”,我的自定义主题不在选项中。我在这里搜索“我的”(它们是 MyLightThemeMyDarkTheme),但我得到的结果为零:


my_themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <attr name="MyCustomAttr" format="reference"/>
    <attr name="MySecondCustomAttr" format="reference"/>

    <style name="MyLightTheme" parent="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
        <item name="MyCustomAttr">@drawable/light_thing</item>
        <item name="MySecondCustomAttr">@drawable/second_light_thing</item>
    </style>

    <style name="MyDarkTheme" parent="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
        <item name="MyCustomAttr">@drawable/dark_thing</item>
        <item name="MySecondCustomAttr">@drawable/second_dark_thing</item>
    </style>

</resources>

主题Presentation子类:

open class MyThemedPresentation(outerContext: Context?, display: Display?, isLight: Boolean)
        : Presentation(outerContext, display, getTheme(isLight)) {

    companion object {

        @StyleRes
        @JvmStatic
        fun getTheme(isLight: Boolean): Int =
            when (isLight) {
                true -> R.style.MyLightTheme
                false -> R.style.MyDarkTheme
            }
    }
}

【问题讨论】:

  • 您的主题是否在同一个模块中声明?通常,如果当前模块看到它们,它们就会出现。如果它们在不同的模块中声明,并且您的模块不依赖于该模块,那么它们将不会被看到(不幸的是)
  • @cjurjiu 是的,它们都在同一个模块中(简单的演示只是一个模块)。感觉就像 Android Studio 只添加了清单中列为主题的样式或类似的东西。

标签: android android-studio android-theme


【解决方案1】:

我一直无法想办法让我的主题出现在我的问题中提到的下拉菜单中,但我能够通过将 tools:theme 属性添加到布局的根视图来解决这个问题.

例如:

tools:theme="@style/MyLightTheme"

那么,无论下拉选择什么主题,布局预览都会使用指定的主题。

【讨论】:

  • 对我来说,我只需要切换限定符,而不是主题。旋转图标下方有一个“夜间主题”子菜单,可让您将其更改为夜间主题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 2018-12-03
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多