Java 如何更改背景形状';以编程的方式改变颜色
我有一个自定义视图,我必须根据输入更改代码中背景形状的颜色 形状:Java 如何更改背景形状';以编程的方式改变颜色,java,android,android-custom-view,Java,Android,Android Custom 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="64d
<?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>
形状的颜色总是
#BBBBBB
。无论我尝试使用哪种颜色相关属性,我都无法将其更改为例如红色。我必须根据输入更改颜色。您可以将颜色过滤器设置为可绘制形状:
Drawable background = getContext().getResources().getDrawable(R.drawable.shape_background);
background.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
this.setBackground(background);
您可以将颜色过滤器设置为可绘制形状:
Drawable background = getContext().getResources().getDrawable(R.drawable.shape_background);
background.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
this.setBackground(background);
您可以使用GradientDrawable Api更改颜色 Xml 有关更多信息,请参阅下面的链接
您可以使用GradientDrawable Api更改颜色 Xml 有关更多信息,请参阅下面的链接
尝试下面的代码,将此代码放入customtextview类中,并根据需要更改背景颜色
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(this,R.color.red_500),
ContextCompat.getColor(this,R.color.red_500), ContextCompat.getColor(this,R.color.red_500)});
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke((int)0.5, ContextCompat.getColor(this, R.color.black));
gd.setCornerRadius(8f);
gd.setBounds(2, 2, 2, 2);
btnCreateUser.setBackground(gd);
尝试下面的代码,将此代码放入customtextview类中,并根据需要更改背景颜色
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(this,R.color.red_500),
ContextCompat.getColor(this,R.color.red_500), ContextCompat.getColor(this,R.color.red_500)});
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke((int)0.5, ContextCompat.getColor(this, R.color.black));
gd.setCornerRadius(8f);
gd.setBounds(2, 2, 2, 2);
btnCreateUser.setBackground(gd);
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(this,R.color.red_500),
ContextCompat.getColor(this,R.color.red_500), ContextCompat.getColor(this,R.color.red_500)});
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke((int)0.5, ContextCompat.getColor(this, R.color.black));
gd.setCornerRadius(8f);
gd.setBounds(2, 2, 2, 2);
btnCreateUser.setBackground(gd);