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 (将#修改为@)