如何更改波纹效果的纯色

时间:2019-10-21 16:15:29

标签: java android user-interface rippledrawable gradientdrawable

我有一个具有3种自定义状态的切换按钮: -按下 -已检查 -已实现

我正在使用以下xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/togglebutton_color_custom_ripple" android:state_pressed="true" />
    <item android:drawable="@drawable/togglebutton_color_custom_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/togglebutton_color_custom_unchecked" />
</selector>

我想以编程方式更改此按钮每种状态的背景颜色。我尝试使用以下代码:

        StateListDrawable drawable = (StateListDrawable) mToggleButtonCustom.getBackground();
        DrawableContainer.DrawableContainerState dcs = (DrawableContainer.DrawableContainerState) drawable.getConstantState();
        Drawable[] drawableItems = dcs.getChildren();

        GradientDrawable gradientDrawablePressed = (GradientDrawable) drawableItems[0];
        GradientDrawable gradientDrawableChecked = (GradientDrawable) drawableItems[1];
        GradientDrawable gradientDrawableUnChecked = (GradientDrawable) drawableItems[2];

        gradientDrawablePressed.setColor(Color.parseColor(color));
        gradientDrawableChecked.setColor(Color.parseColor(color));
        gradientDrawableUnChecked.setColor(Color.parseColor(color));

它在“已检查”和“释放”状态下工作良好,因为我在XML中使用经典形状,但在“按下”状态下却不工作,因为我在XML中使用了以下波纹效果:

<?xml version="1.0" encoding="utf-8"?>
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/ripple">
    <item>
        <shape android:shape="oval">
            <size
                android:height="@dimen/togglebutton_size"
                android:width="@dimen/togglebutton_size" />
            <solid android:color="@color/blue_vs"/>
            <stroke android:width="@dimen/togglebutton_button_stroke"
                android:color="@color/white" />
        </shape>
    </item>
</ripple>

似乎我必须在代码中使用“ RippleDrawable”,但我不太了解如何,我只是想更改纯背景颜色,而不是波纹颜色或笔触。

谢谢

0 个答案:

没有答案