我有一个名为dot的类,该应用程序运行时会创建同一类的许多实例。问题是我需要能够单击此类的一个实例,并使单击的实例仅更改颜色。
问题是,每当我单击一个点实例时,它们都会改变颜色,而不仅仅是我单击的一个。
这是代码:
package com.ewebapps;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
public class Dot extends View {
private final float x;
private final float y;
private final int r;
private final Paint mBlack = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint mWhite = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint mGreen = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean touched;
public Dot(Context context, float x, float y, int r) {
super(context);
mBlack.setColor(0xFF000000); //Black
mWhite.setColor(0xFFFFFFFF); //White
mGreen.setColor(0xFF00FF00); //Green
this.x = x;
this.y = y;
this.r = r;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) { // On touch.
touched = true;
//mPaint.setColor(0xFF00FF00); // Turn dot green.
this.invalidate();
return super.dispatchTouchEvent(event);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r+2, mWhite); //White stroke.
if(!touched)
{
canvas.drawCircle(x, y, r, mBlack); //Black circle.
}
else
{
canvas.drawCircle(x, y, r, mGreen); //Green circle.
}
}
}
最佳答案
我们不知道您如何声明或调用或创建这些视图,因此我们也不知道如何为您提供帮助。
我唯一能说的是dispatchTouchEvent与onTouchEvent不一样
看起来只要屏幕上而不是您身上有任何触摸事件,就会调用dispatchTouchEvent。因此,所有视图都将接收touch事件,然后将其设置为true。Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.