java - 如何以编程方式更改背景形状的颜色

标签 java android android-custom-view

我有一个自定义 View ,我必须根据输入从代码中更改背景形状的颜色。

形状:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size
        android:width="64dp"
        android:height="64dp" />
    <solid
        android:color="#BBBBBB" />
</shape>

自定义 View :

public class MyCustomView extends TextView {

    public MyCustomView(Context context) {
        super(context);
    }

    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void setCustomValue(long customValue) {
        this.setBackgroundResource(R.drawable.shape_background);
        this.setTextColor(getColor(R.color.colorCustomViewText));
        this.setGravity(Gravity.CENTER);
        this.setText(String.valueOf(customValue));
    }

    public long getCustomValue() {
        return Long.parseLong(this.getText().toString());
    }

    private int getColor(int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return getContext().getColor(colorId);
        } else {
            return getContext().getResources().getColor(colorId);
        }
    }
}

形状的颜色始终为#BBBBBB。我无法将其更改为例如red 无论我尝试哪种颜色相关属性。我必须根据输入更改颜色。

最佳答案

您可以为您的可绘制形状设置滤色器:

Drawable background = getContext().getResources().getDrawable(R.drawable.shape_background);
background.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
this.setBackground(background);

关于java - 如何以编程方式更改背景形状的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43695758/

相关文章:

java - IME 的自定义 Android View 的一部分被切断?

java - Android 应用程序空白但不在设计器中?

java - Android - 自定义 View - 使用顶部 View 扩展 EditText

java - 通过套接字和流的 JAXB - 阅读器 block

java - 为什么@Autowired注释将同一类的每个bean关联到context.xml中?

java - 硬件后退按钮无法返回上一页

java - NestedScrollView 中的多个 Recyclerview 不会发生 View 回收

Android CustomView 显示两次

java - 编辑 TableColumn 时出现 ClassCastException

java - 在 GWT 中创建 JSON 字符串的更好方法?