Android 以编程方式使用主题值

问题描述 投票:0回答:1

我想在主题中创建一个样式并在代码中使用它的值,如下所示:

        val bgColor = LIST_ITEM_BG_COLOR;
        val textColor = LIST_ITEM_TEXT_COLOR
        val strokeColor = LIST_ITEM_STROKE_COLOR

这是我的主题文件(还有与此类似的主题(夜间)文件):

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Base.Theme.GuitarComposer" parent="Theme.Material3.DayNight.NoActionBar">
        <!-- Customize your light theme here. -->
        <!-- <item name="colorPrimary">@color/my_light_primary</item> -->
    </style>

    <style name="ListItem">
        <item name="android:background">@color/component_background</item>
        <item name="android:textColor">@color/text</item>
        <item name="android:strokeColor">@color/border_color</item>
    </style>

    <style name="Theme.GuitarComposer" parent="Base.Theme.GuitarComposer" />
</resources>

我还没有找到任何关于如何在代码中正确使用主题样式的解释..仅在 xaml 上 希望有人能帮助我,谢谢。

android android-theme android-styles
1个回答
0
投票

尝试使用这个:

val typedValue = TypedValue();
theme.resolveAttribute(R.attr.strokeColor, typedValue, true);
val strokeColor  = ContextCompat.getColor(this, typedValue.resourceId)
© www.soinside.com 2019 - 2024. All rights reserved.