目前在我的Android应用程序中,我使用两种不同颜色的8个矩形块创建了一个自定义视图。我想要做的是使8矩形根据数组更改更新颜色。现在我的代码自爆可以创建静态视图,如何使其动态更改,另一个类可以操作此视图类对象。
public class SampleCanvasActivity extends View {
Paint paint = new Paint();
int array[] = new int[8];
public SampleCanvasActivity(Context context,AttributeSet attributeSet) {
super(context,attributeSet);
}
@Override
public void onDraw(Canvas canvas) {
/*
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
canvas.drawRect(130, 130, 180, 180, paint);
paint.setStrokeWidth(0);
paint.setColor(Color.CYAN);
canvas.drawRect(133, 160, 177, 177, paint );
paint.setColor(Color.YELLOW);
canvas.drawRect(133, 133, 177, 160, paint );
*/
for(int i=0;i<array.length;i++){
array[i] = 0;
}
array[7] = 1;
int left = 50; // initial start position of rectangles (50 pixels from left)
int top = 50; // 50 pixels from the top
int width = 50;
int height = 50;
for (int row = 0; row < 2; row++) { // draw 2 rows
left = 50;
for(int col = 0; col < 4; col++) { // draw 4 columns
int id = row*4 + col;
if(array[id]==0)
paint.setColor(Color.parseColor("#CD5C5C"));
else
paint.setColor(Color.CYAN);
canvas.drawRect(left, top, left+width, top+height, paint);
left = (left + width + 10); // set new left co-ordinate + 10 pixel gap
// Do other things here
// i.e. change colour
}
top = top + height + 10; // move to new row by changing the top co-ordinate
}
}
}
答案 0 :(得分:0)
您可以在自定义视图中使用参数,并在xml中定义attr
。
<resources>
<declare-styleable name="YourStyle">
<attr name="YourColor" format="color"></attr>
</declare-styleable>
</resources>
在SampleCanvasActivity中,
在构造函数中获取参数
TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.YourStyle);
Resources mResources = context.getResources();
yourcolor = mTypedArray.getColor(R.styleable.YourStyle_YourColor, mResources.getColor(R.color.YourColor));
为你的颜色添加一个setter
public void setYourColor(int innerCircleColor) {
this. yourcolor = yourcolor;
invalidate();
}
最后,在onDraw
paint.setColor(yourcolor);
更改数组后,请致电setYourColor
。