Android SWITCH.如何将开启颜色更改为绿色

use*_*473 6 layout android

下面是将开关添加到表格布局的代码.当开关触摸时,它变为红色.我需要它是绿色的.

我已经尝试了一切将ON颜色改为绿色但没有成功.

 Switch sw1 = new Switch(this);
 sw1.setTag(i);
 if (switchonoff.get(i).equals("true"))
        {
            sw1.setChecked(true);

        }
        else
        {
           sw1.setChecked(false);
         }
        sw1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
             {
                @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                    {
                        System.out.println("____Switch State: isChecked: " + isChecked +  " " + buttonView.getTag() );
                        Integer tmpint = (Integer)buttonView.getTag();
                        if (isChecked)
                        {
                            switchonoff.set(tmpint, "true");
                        }
                        else
                        {
                            switchonoff.set(tmpint, "false");
                        }

                        for (int i=0; i<mnumberofrows; i++ )
                        {
                            System.out.println("________Switch State: isChecked " + i + " " + switchonoff.get(i));
                        }
                    }
                });
Run Code Online (Sandbox Code Playgroud)

bas*_*sic 29

开关的颜色取决于应用的主题或风格.您需要创建自定义样式并将其应用于您的交换机.同

使用以下内容编辑values\styles.xml

<style name="SwitchTheme" parent="Theme.AppCompat.Light">
    <item name="android:colorControlActivated">#148E13</item>
</style>
Run Code Online (Sandbox Code Playgroud)

现在我们只需要将它应用于交换机.

<Switch
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="New Switch"
  android:id="@+id/switch1"
  android:theme="@style/SwitchTheme" <--- Important line
  android:layout_alignParentTop="true"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="78dp" />
Run Code Online (Sandbox Code Playgroud)

然后我们留下以下内容:

之前

在此输入图像描述

在此输入图像描述

  • 需要最小api级别21.建议api级别为14 (4认同)
  • 对于最小api级别,使用'<item name ="colorControlActivated">#148E13 </ item>'insted of'<item name ="android:colorControlActivated">#148E13 </ item>' (2认同)

ole*_*234 5

这个答案将帮助那些将使用SwitchMaterial而不是Switch

下面是 XML 格式的示例SwitchMaterial。设置自定义主题,如 xml 最后一行所示

<com.google.android.material.switchmaterial.SwitchMaterial
    android:id="@+id/switchLocks"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/filter_lock_title"
    android:theme="@style/FilterSwitchThemeGreen" />
Run Code Online (Sandbox Code Playgroud)

在您values/styles.xml的开关中添加样式。

<style name="FilterSwitchThemeGreen" parent="AppTheme">
    <item name="colorAccent">#00FF00</item>
</style>
Run Code Online (Sandbox Code Playgroud)

前:红色开关

后:绿色开关