我有一个名为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。因此,您的所有视图都将收到触摸事件,然后设置为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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top