简体   繁体   中英

How to choose my Theme in Android Studio layout preview

In my project's res/values directory, I have a my_themes.xml file that specifies custom attributes and two custom themes (light and dark). These themes get applied (in code) to Presentation objects by way of the third constructor parameter .

I would like to be able to choose either of my two themes when I am editing my layout files, and see the themed results in the layout preview. When I run the code, everything works fine; this is just a question about how to get the layout preview to show me my theme.

It does not seem possible to choose my custom themes, however. When I click the dropdown to select the theme to use, only my "default" AppTheme (and its parents) are visible:

在此处输入图片说明

If I click into "More themes...", my custom themes are not among the options. Here I am searching for "My" (they are MyLightTheme and MyDarkTheme ), but I get zero results:

在此处输入图片说明


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>

Themed Presentation subclass:

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
            }
    }
}

I have been unable to figure out a way to get my themes to appear in the dropdown menu mentioned in my question, but I was able to work around the issue by adding the tools:theme attribute to the root view of the layout.

For example:

tools:theme="@style/MyLightTheme"

Then, regardless of what theme is selected in the dropdown, the layout preview will use the specified theme.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM