我有一個名爲dot的類,並且該應用程序運行時會創建該同一類的許多實例。問題是我需要能夠點擊這個類的其中一個實例,並且點擊的實例只能改變顏色。private dispatchTouchEvent?
問題是每當我點擊其中一個點實例時,它們都會改變顏色,而不是我點擊的顏色。
下面的代碼:
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.
}
}
}
這是被稱爲在一個單獨的類來創建一個這個「點」對象的代碼,它被稱爲通過環形創建其中許多多次:的FrameLayout主=(的FrameLayout)findViewById(R .id.main_view); main.addView(new Dot(this,x,y,25)); – Eweb 2010-11-04 21:05:04
感謝大家,我大部分都瞭解你所解釋的事情正在發生,但我想知道你是否可以給我一個我應該怎樣解決它的簡短描述?也許有一些示例代碼和它應該放在哪裏?如果不是這樣,但它會有很大的幫助!謝謝! – Eweb 2010-11-05 02:22:46
你應該讓你的視圖類實現OnTouchListener – Falmarri 2010-11-05 17:30:58