android - 如何更改布局文件中可绘制形状的颜色

标签 android android-layout

我创建了一个可绘制的圆形。我将其用作线性布局的背景。它工作正常。但问题是,我想创建 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>

我想使用不同颜色的可绘制圆形来创建此布局。

布局: enter image description here

最佳答案

您可以通过为所有按钮设置相同的可绘制对象(您提供的那个),然后在您的代码中:

例子:

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/

相关文章:

android - Nexus 4 屏幕底部 96 像素缺失 - 获取 Nexus 4 的窗口尺寸

iphone - 确定 iPhone 和 Android 的唯一蓝牙 MAC 地址

android - 主机未解析 : imap. gmail.com:993

android - 从 native 代码访问 android 外部 SD 卡

android - 无法找到 com/razorpay/Y_$B$$5 的外部类 com/razorpay/Y_$B$

android - KitKat 中的半透明系统栏和内容边距

android - sw720dp 和 xlarge 布局文件夹区别

android - 引入ConstraintLayout之后再有RelativeLayout有什么好处?

Android 在不使用 XML 的情况下指定像素单位(如 sp、px、dp)

php - 强制关闭 PHP、MySQL 和 SQLite 的 Android 登录和注册