Anyone know how to attach a touch listener to this class?
package com.ewebapps;
import android.content.Context;
import android.graphics.Canv开发者_开发知识库as;
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.
}
}
Well... when creating your own views, the best way to accomplish that is overriding the dispatchTouchEvent
method. Trust me, using setOnTouchListener
and onTouchEvent
don't work well in some scenarios. This is all you have to do in your View
:
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// put your logic here
return super.dispatchTouchEvent(event);
}
documentation with example
View aView = (View)findViewById(R.id.DotView);
aView.setOnTouchListener(this);
Full Example Here
Aaron Saunders answer works for views(like buttons) because an onTouchListener only tells you what view was clicked and not exactly where. If you need to know exactly where the event was without creating buttons try this in your activity class:
@Override
onTouchEvent(MotionEvent event) {
int _x = event.getX();
int _y = event.getY();
// do stuff
}
Note: onTouchEvent is only called when the event is NOT handled by a view.
Documentation
(Can someone tell me how to add line breaks?)
精彩评论