如何使用RippleDrawable以编程方式设置按钮背景(API 21)

Zak*_*rdi 2 android android-layout android-drawable android-5.0-lollipop

我继承了Button.从该类中我尝试以编程方式更改颜色.

RippleDrawable draw = (RippleDrawable) getContext().getApplicationContext()
    .getResources().getDrawable(R.drawable.raised_btn);
this.setBackground(draw);
Run Code Online (Sandbox Code Playgroud)

到目前为止看起来很棒

默认状态

但是我按下按钮,它是最随机的颜色.我没有指定这些粉红色的颜色.如果我通过XML(android:background="@drawable/raised_btn")将这个drawable设置为背景,那么我没有问题.我需要以编程方式设置它.

压制状态


我的RippleDrawable-raised_btn.xml

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
    <inset xmlns:android="http://schemas.android.com/apk/res/android"
        android:insetLeft="@dimen/button_inset_horizontal_material"
        android:insetTop="@dimen/button_inset_vertical_material"
        android:insetRight="@dimen/button_inset_horizontal_material"
        android:insetBottom="@dimen/button_inset_vertical_material">
        <shape android:shape="rectangle">
            <corners android:radius="@dimen/control_corner_material" />
            <solid android:color="@color/tan"/>
            <padding android:left="@dimen/button_padding_horizontal_material"
                android:top="@dimen/button_padding_vertical_material"
                android:right="@dimen/button_padding_horizontal_material"
                android:bottom="@dimen/button_padding_vertical_material" />
        </shape>
    </inset>
</ripple>
Run Code Online (Sandbox Code Playgroud)

如何以RippleDrawable编程方式设置背景时如何实现正确的连锁效果?

ala*_*anv 5

Resources对象不了解活动主题.你需要从获得绘制Context或传递ThemeResources.getDrawable(int,Theme)对主题属性得到解决秩序.

Context ctx = getContext();

// The simplest use case:
RippleDrawable dr1 = (RippleDrawable) ctx.getDrawable(R.drawable.raised_btn);

// Also valid:
Resources res = ctx.getResources();
RippleDrawable dr2 =
    (RippleDrawable) res.getDrawable(R.drawable.raised_btn, ctx.getTheme());

// If you're using support lib:
Drawable dr3 = ContextCompat.getDrawable(ctx, R.drawable.raised_btn);
Run Code Online (Sandbox Code Playgroud)

此外,没有理由在这里使用应用程序上下文.如果有的话,这会让您更有可能将用于解析属性的主题与用于扩展您正在传递绘图的任何视图的主题相匹配.