我有一个名为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.
}
}
}
答案 0 :(得分:2)
我们不知道你是如何宣布或致电或创建这些观点的,所以我们不知道如何帮助你。
我唯一可以说的是dispatchTouchEvent与onTouchEvent不同
每当屏幕上出现任何触摸事件时,就会调用dispatchTouchEvent,而不是在你身上。所以你的所有观点都在接收触摸事件,然后设置为真。
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.