我正在创建带有网格的相机应用程序,我希望用户能够通过单击他想要使用的颜色的按钮来更改网格的颜色。网格是使用 onDraw 创建的,它位于 DrawGrid 类中,此类是从 GridMenuFragment 片段中调用的,而颜色按钮位于 ColorFragment 片段中。
现在,我成功地将我想要使用的颜色传递给了DrawGrid,但它没有更新,网格的颜色也没有改变。我在 setCurrentColor 方法中使用 invalidate() 。我尝试用与更改网格相同的方式更改颜色,但它不起作用。任何帮助将不胜感激。
这里是DrawGird.java代码:
public class DrawGrid extends View {
int whichGrid;
Paint paint;
int currentColor=Color.WHITE;
public DrawGrid(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
paint.setColor(currentColor);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
}
public void setWhichGrid(int number) {
whichGrid = number;
invalidate();
}
public void setCurrentColor(int color) {
switch(color){
case 0:
currentColor=Color.WHITE;
break;
case 1:
currentColor=Color.RED;
break;
case 2:
currentColor=Color.BLUE;
break;
}
paint.setColor(currentColor);
invalidate();
Log.d("DrawGrid", "currentColor is now1 " + currentColor);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Path path = new Path();
int width = getWidth();
int height = getHeight();
switch (whichGrid) {
case 1:
float lineV1 = width / 3f;
float lineV2 = (width / 3f) * 2f;
float lineH1 = height / 3f;
float lineH2 = (height / 3f) * 2f;
Log.d("DrawGrid", "currentColor is now3 " + currentColor);
canvas.drawLine(lineV1, 0, lineV1, height, paint);
canvas.drawLine(lineV2, 0, lineV2, height, paint);
canvas.drawLine(0, lineH1, width, lineH1, paint);
canvas.drawLine(0, lineH2, width, lineH2, paint);
break;
case 2:
float lineV = width / 3f;
float lineH = height / 3f;
canvas.drawLine(lineV, 0, lineV, height, paint);
canvas.drawLine(0, lineH, width, lineH, paint);
break;
}
}
}