有人知道如何将触摸监听器附加到此类吗?
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.
}
}
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.
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯...创建自己的视图时,实现此目的的最佳方法是重写
dispatchTouchEvent
方法。相信我,使用setOnTouchListener
和onTouchEvent
在某些情况下效果不佳。这就是您在View
中需要做的全部事情:Well... when creating your own views, the best way to accomplish that is overriding the
dispatchTouchEvent
method. Trust me, usingsetOnTouchListener
andonTouchEvent
don't work well in some scenarios. This is all you have to do in yourView
:带有示例的文档
这里有完整示例
documentation with example
Full Example Here
Aaron Saunders 的答案适用于视图(如按钮),因为 onTouchListener 只告诉您单击了哪个视图,而不是确切的位置。如果您需要确切地知道事件发生的位置而不创建按钮,请在您的活动类中尝试以下操作:
@覆盖
onTouchEvent(MotionEvent 事件) {
int _x = event.getX();
int _y = event.getY();
// 做事
}
注意:仅当事件未由视图处理时才会调用 onTouchEvent。
文档< /strong>
(有人可以告诉我如何添加换行符吗?)
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?)