android - 以编程方式设置 android 形状颜色

标签 android android-layout shapes

我正在编辑以使问题更简单,希望这有助于获得准确的答案。

假设我有以下 oval 形状:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:angle="270"
           android:color="#FFFF0000"/>
    <stroke android:width="3dp"
            android:color="#FFAA0055"/>
</shape>

如何在 Activity 类中以编程方式设置颜色?

最佳答案

注意:答案已更新以涵盖 backgroundColorDrawable 实例的情况>。谢谢 Tyler Pfaff , 指出这一点。

The drawable is an oval and is the background of an ImageView

使用 getBackground()imageView 获取 Drawable:

Drawable background = imageView.getBackground();

检查通常的嫌疑人:

if (background instanceof ShapeDrawable) {
    // cast to 'ShapeDrawable'
    ShapeDrawable shapeDrawable = (ShapeDrawable) background;
    shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    // cast to 'GradientDrawable'
    GradientDrawable gradientDrawable = (GradientDrawable) background;
    gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    // alpha value may need to be set again after this call
    ColorDrawable colorDrawable = (ColorDrawable) background;
    colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

精简版:

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

请注意,不需要检查空值。

但是,如果在其他地方使用它们,您应该在修改它们之前在可绘制对象上使用 mutate()。 (默认情况下,从 XML 加载的可绘制对象共享相同的状态。)

关于android - 以编程方式设置 android 形状颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17823451/

相关文章:

android - 从自定义适配器更新后 ListView 回到第一个位置

android - 色差atan和atan2结果差异

java - Android : How to get just two digit after the point in decimal value ? 不想截断值

java - 如何根据给编辑 TextView 的计数值动态实现线性布局的代码

android - 如何在圆上画新月形状

visio - 在哪里可以找到用于软件开发的 visio 形状?

java - 在 android webview 中禁用弹出窗口和警报框

java - Android应用程序: Error: Android.数据库。CursorIndexOutOfBoundsException : Index 0 requested,,大小为0

FragmentDialog 中的 Android Google map 被 Dialog 自己的灰色覆盖层覆盖

java - 从 2 个特定点创建一个矩形