3

我的问题可能最好从视觉上提出——我希望SwitchCompat开关看起来像他们在 Android 设置应用程序中所做的那样:

这是关闭的:

在此处输入图像描述

这是在:

在此处输入图像描述

但由于某种原因,我的SwitchCompat开关在关闭时看起来像这样:

在此处输入图像描述

没有灰色的“轨道”延伸到右侧。但是,当打开时,它看起来像预期的那样:

在此处输入图像描述

如您所见,我已将自定义色调应用于我的应用程序。我的自定义色调应用如下:

<activity
    android:name=".editor.MySettingsEditor"
    android:theme="@style/Theme.MyCustomTheme" />

然后,在styles.xml 中:

<style name="Theme.MyCustomTheme" parent="Theme.AppCompat">    
    <item name="colorAccent">@color/myColorAccent</item>
    <item name="colorPrimary">@color/myColorPrimary</item>
    <item name="colorPrimaryDark">@color/myColorPrimaryDark</item>
    <item name="alertDialogTheme">@style/AppCompatAlertDialogStyle</item>
</style>

为确保不是我的自定义样式导致此问题,我通过以下操作将其删除:

<activity
    android:name=".editor.MySettingsEditor"
    android:theme="@style/Theme.AppCompat" />

但是,“关闭”轨道仍然没有显示,尽管色调现在变成了 Android 默认的蓝绿色。

在此处输入图像描述 在此处输入图像描述

为什么我的SwitchCompat开关在关闭状态时会丢失灰色轨迹?

描述 SwitchCompat 的 XML 非常简单:

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"/>

谢谢!

4

2 回答 2

6

您可以通过设置colorControlActivated活动颜色和colorSwitchThumbNormal非活动颜色来应用自定义色调。如果要更改轨道颜色,则可以设置android:colorForeground

<style name="CustomSwitch" parent="Theme.AppCompat">  
    <!-- active thumb-->
    <item name="colorControlActivated">@color/active_switch_color</item>

    <!-- inactive thumb-->
    <item name="colorSwitchThumbNormal">@color/inactive_switch_color</item>

    <!-- inactive track color -->
    <item name="android:colorForeground">@color/inactive_track_color</item>
</style>  

如果您想将自定义主题直接设置为您的视图:

<android.support.v7.widget.SwitchCompat
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:theme="@style/CustomSwitch"/>
于 2016-04-16T20:03:05.557 回答
1

@esilver 如果您想动态处理它们,也许是更好的方法

试试这个……我已经测试过了,它工作得很好

public class MainActivity extends AppCompatActivity {
    int[][] states = new int[][] {
            new int[] {-android.R.attr.state_checked},
            new int[] {android.R.attr.state_checked},
    };

    int[] thumbColors = new int[] {
            Color.BLACK,
            Color.RED,
    };

    int[] trackColors = new int[] {
            Color.GREEN,
            Color.BLUE,
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch);
        DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getThumbDrawable()), new ColorStateList(states, thumbColors));
        DrawableCompat.setTintList(DrawableCompat.wrap(switchCompat.getTrackDrawable()), new ColorStateList(states, trackColors));
    }
}

您只需要根据您的要求/需要更新“trackColors”和“thumbColor”。

于 2017-01-24T04:31:07.053 回答