Android 以编程方式设置形状颜色
我使用的是键盘视图,其中我有自定义的xml形状,我可以设置特定的按钮这里的颜色是我的形状xml:Android 以编程方式设置形状颜色,android,android-layout,Android,Android Layout,我使用的是键盘视图,其中我有自定义的xml形状,我可以设置特定的按钮这里的颜色是我的形状xml: <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#80B3B3B3"/> <corners android:bottomRightRadiu
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#80B3B3B3"/>
<corners android:bottomRightRadius="2dp" android:bottomLeftRadius="2dp"
android:topLeftRadius="2dp" android:topRightRadius="2dp"/>
</shape>
@Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
List<Key> keys = getKeyboard().getKeys();
for (Key key : keys) {
Drawable dr = (Drawable)this.getResources().getDrawable(R.drawable.keyshape);
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
}
}
现在,我想允许用户设置形状的颜色。您知道如何在绘图前设置形状颜色吗?您不能按语法更改形状颜色,或者您必须使用不同的颜色创建新形状,或者您可以使用:
imageView.getBackground().setColorFilter(Color.parseColor("#BBBDBF"), Mode.MULTIPLY);
imageview.invalidate();
它会将给定的颜色代码与您的图像背景相乘,并显示颜色更改的效果。首先,您应该创建一个您想要设置和扩展它的自定义视图(TextView或按钮w/e我将编写示例作为扩展视图),因为您无法以编程方式编辑形状xml,所以您将创建它作为一个整体 覆盖视图所需的行为和构造函数。现在您将创建一个方法SetGradientColor,该方法将两种颜色作为int值(底部和顶部渐变颜色)。也可以修改它以设置圆角的半径
public class GradientView extends View{
public GradientView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public GradientView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public GradientView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public void setGradientColors(int bottomColor, int topColor) {
GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] {bottomColor, topColor});
gradient.setShape(GradientDrawable.RECTANGLE);
gradient.setCornerRadius(10.f);
this.setBackgroundDrawable(gradient);
}
}
您将使用此新视图并以编程方式将形状设置为:
GradientView view = (GradientView) findViewById(R.id.customView);
// bottom color - top color order
view.setGradientColors(Color.parseColor("#ff0000"), Color.parseColor("#0000ff"));
如果您需要进一步的帮助和关于基础知识的完整解释,我在我的项目中通过遵循此
希望它也能对您有所帮助。如果您只想更改xml drawable中形状上的颜色,我将您的onDraw做了一些更改。 如果您使用
标记在xml中定义它,它将是一个
Drawable dr = this.getResources().getDrawable(R.drawable.keyshape);
if (dr instanceof GradientDrawable) {
GradientDrawable gradientDr = (GradientDrawable) dr;
gradientDr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
gradientDr.setColor(Color.GREEN);
gradientDr.draw(canvas);
}