setColorFilter to Button而不改变笔画

问题描述 投票:2回答:2

我有一个带按钮的xml,背景可绘制为:

<shape android:shape="rectangle">
            <corners android:bottomRightRadius="20dp"
                android:topLeftRadius="20dp"/>
            <stroke android:width="1dp" android:color="@color/black"/>
 </shape>

我想以编程方式仅更改按钮背景的颜色。所以我试过这个,

button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.red), PorterDuff.Mode.SRC_ATOP);

但是,当我使用setColorFIlter()时,我根本看不到笔画。任何输入?

android android-drawable android-button
2个回答
0
投票

这不是你问题的最佳解决方案,但肯定是它的工作

RippleDrawable rippleImgStart;  
Drawable imgStart;
 final int ColorWhiteOpacity = Color.argb(75,255,255,255); 
 imgStart = ContextCompat.getDrawable(this, R.drawable.start); 
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            rippleImgStart = new
                    RippleDrawable(ColorStateList.valueOf(ColorWhiteOpacity), imgStart, null);
            btn.setImageDrawable(rippleImgStart);
}

这基本上用于为图像提供连锁效果,所以你也可以实现连锁效果。

和ColorWhiteOpacity,您可以使用您的颜色并将其设置为图像。

在这里你可以找到例子:link


0
投票

这对我有用。

GradientDrawable buttonBackground = (GradientDrawable)button.getBackground();
buttonBackground.setColor(color);
© www.soinside.com 2019 - 2024. All rights reserved.