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

标签 android android-layout android-5.0-lollipop android-drawable

我对Button进行了子类化。在该类中,我尝试以编程方式更改颜色。

RippleDrawable draw = (RippleDrawable) getContext().getApplicationContext()
    .getResources().getDrawable(R.drawable.raised_btn);
this.setBackground(draw);

到目前为止看起来很棒..

Default State

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

Pressed State


我的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>

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

最佳答案

Resources 对象不了解 Activity 主题。您需要从 Context 获取可绘制对象或将 Theme 传递到 Resources.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);

此外,没有理由在此处使用应用程序上下文。如果有什么不同的话,那就是您用来解析属性的主题与用于膨胀您将可绘制对象传递到的任何 View 的主题不匹配的可能性更大。

关于android - 如何使用 RippleDrawable (API 21) 以编程方式设置按钮背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28710106/

相关文章:

android - 将所有设置从 Eclipse 导入到 Android Studio

java - 如何将数据从非 Activity 类传递到android中的 Activity ?

java - 有人可以帮助我理解调用 Intent 来选择文件吗?

java - Imageview 没有显示我的图像?

android - Android Lollipop 上的海拔不工作

android - Android 中的 TImeBased 触发器

android - 如何在我的 android 应用程序主屏幕中实现以下转换?

android-studio - Android Studio ActivityMain.kt 未从 Activity-main.xml 中找到 TextView、按钮等的 ID

java - Android API 21 只允许创建空 Activity

android - 如何实现像 Lollipop 这样的联系人详细信息屏幕