我创建了一个可绘制的圆形。我将其用作线性布局的背景。它工作正常。但问题是,我想创建 6 个不同颜色的圆圈。那么我可以只使用一个可绘制形状并为不同的圆圈更改其颜色吗?
这是我的可绘制圆形
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<solid
android:color="@color/colorPrimary"
/>
<size
android:width="30dp"
android:height="30dp"/>
</shape>
我想使用不同颜色的可绘制圆形来创建此布局。
最佳答案
您可以通过为所有按钮设置相同的可绘制对象(您提供的那个),然后在您的代码中:
例子:
Drawable mDrawable = ContextCompat.getDrawable(context, R.drawable.yourDrawable);
mDrawable.setColorFilter(new PorterDuffColorFilter(yourColorInt,PorterDuff.Mode.MULTIPLY));
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
yourButton.setBackgroundDrawable(mDrawable);
} else {
yourButton.setBackground(mDrawable);
}
为您的每个按钮执行此操作,但请记住将 yourColorInt
替换为您要应用它的按钮的颜色。
关于android - 如何更改布局文件中可绘制形状的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40188610/