任何人都知道如何将触摸倾听者附加到这个课程?

时间:2010-11-01 23:27:24

标签: android class view extend ontouchlistener

package com.ewebapps;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

public class Dot extends View {
     private final float x;
     private final float y;
     private final int r;
     private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
     private final Paint mWhite = new Paint(Paint.ANTI_ALIAS_FLAG);

     public Dot(Context context, float x, float y, int r) {
         super(context);
         mPaint.setColor(0xFF000000); //Black
         mWhite.setColor(0xFFFFFFFF); //White
         this.x = x;
         this.y = y;
         this.r = r;
     }

     @Override
     protected void onDraw(Canvas canvas) {
         super.onDraw(canvas);
         canvas.drawCircle(x, y, r+2, mWhite); //White stroke.
         canvas.drawCircle(x, y, r, mPaint); //Black circle.
     }

}

3 个答案:

答案 0 :(得分:1)

嗯......在创建自己的视图时,最好的方法是覆盖dispatchTouchEvent方法。相信我,使用setOnTouchListeneronTouchEvent在某些情况下效果不佳。您只需在View

中执行此操作即可
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    // put your logic here  

    return super.dispatchTouchEvent(event);
}

答案 1 :(得分:0)

documentation with example

View aView = (View)findViewById(R.id.DotView);
aView.setOnTouchListener(this);

Full Example Here

答案 2 :(得分:0)

Aaron Saunders的回答适用于视图(如按钮),因为onTouchListener只会告诉您单击了哪个视图而不是确切位置。如果您需要确定事件的确切位置而不创建按钮,请在您的活动类中尝试:

@Override onTouchEvent(MotionEvent event) { int _x = event.getX();
int _y = event.getY(); // do stuff }

注意:只有在视图未处理事件时才会调用onTouchEvent 的 Documentation

有人可以告诉我如何添加换行符吗?