微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Kotlin - 如何动态更改 SwitchCompat 样式

如何解决Kotlin - 如何动态更改 SwitchCompat 样式

我有一个 <androidx.appcompat.widget.SwitchCompat,我需要使用 kotlin 以编程方式更改 theme 属性的值。

下面是我的自定义开关:

<androidx.appcompat.widget.SwitchCompat
    android:id="@+id/switch_me"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/some_text"
    android:textColor="@color/white"
    android:theme="@style/SwitchTheme1" />

这是我的两种不同风格:

<style name="SwitchTheme1" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorControlActivated">@color/white</item>
    <item name="trackTint">@color/colorPrimary1</item>
</style>

<style name="SwitchTheme2" parent="ThemeOverlay.AppCompat.Light">
    <item name="colorControlActivated">@color/white</item>
    <item name="trackTint">@color/colorPrimary2</item>
</style>

我只需要使用以下代码根据特定条件设置 SwitchTheme1SwitchTheme2

override fun onCreateView( inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle? ): View? {
    val view = inflater.inflate(R.layout.fragment_settings,container,false)
    if(some_condition == "my value"){
       /*Set SwitchTheme1*/
    }else{
       /*Set SwitchTheme2*/
    }
    return view
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。