[英]Not all touch events being received by Android view
在我的Android应用中,我有一个自定义的View
,可以接收触摸事件。 但是,它不会在我每次触摸时都做出反应-只是有时。 据我所知,如果我触摸屏幕,先移动手指,然后放开-即使我只移动一点,事件也会被拾取,但是如果我点击屏幕的速度太快,手指无法在屏幕上滑动, 什么都没发生。 我怎样才能解决这个问题?
这是View的代码:
public class SpeedShooterGameView extends GameActivity.GameView {
public SpeedShooterGameView(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
@Override
protected GameThread getNewThread(SurfaceHolder holder, Context context) {
return new SpeedShooterGameThread(holder, context);
}
// Program is driven by screen touches
public boolean onTouchEvent(MotionEvent event) {
SpeedShooterGameThread thread = (SpeedShooterGameThread) getThread();
if (thread.isRunning()) {
return thread.recieveTouch(event);
} else {
return false;
}
}
}
我非常有信心在SpeedShooterGameThread thread = (SpeedShooterGameThread) getThread();
行中返回的对象SpeedShooterGameThread thread = (SpeedShooterGameThread) getThread();
可以正常工作,但是如果上面的代码看起来不错,我也将发布该类中的相关代码。 当thread.recieveTouch(event);
调用后, MotionEvent
将被发送到另一个线程。
编辑:我将继续发布SpeedShooterGameThread
的代码:
public class SpeedShooterGameThread extends GameActivity.GameView.GameThread {
//... snip ...
private Queue<MotionEvent> touchEventQueue;
//... snip ...
public synchronized final void newGame() { //called from the constructor, used to go to a known stable state
//... snip ...
touchEventQueue = new LinkedList<MotionEvent>();
//... snip ...
}
//...snip...
public synchronized boolean recieveTouch(MotionEvent event) {
return touchEventQueue.offer(event);
}
private synchronized void processTouchEvents() {
synchronized (touchEventQueue) {
while (!touchEventQueue.isEmpty()) {
MotionEvent event = touchEventQueue.poll();
if (event == null) {
continue;
}
//... snip ....
}
}
}
//... snip ...
}
我通过完全Queue<MotionEvent>
修复了该错误。 我的代码现在看起来像这样:
线程不再使用Queue
,并且MotionEvents
时立即得到处理recieveTouch()
被调用:
public class SpeedShooterGameThread extends GameActivity.GameView.GameThread {
//The touchEvent member has been removed.
//... snip ...
public synchronized final void newGame() { //called from the constructor, used to go to a known stable state
// touchEvents is no longer initialized.
//...snip...
}
//...snip...
public synchronized boolean recieveTouch(MotionEvent event) {
//Immediately handle the MotionEvent here,
//or return false if the event isn't processed
}
// The processTouchEvents() method is removed.
//... snip ...
}
该视图不变:
public class SpeedShooterGameView extends GameActivity.GameView {
public SpeedShooterGameView(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
}
@Override
protected GameThread getNewThread(SurfaceHolder holder, Context context) {
return new SpeedShooterGameThread(holder, context);
}
// Program is driven by screen touches
public boolean onTouchEvent(MotionEvent event) {
SpeedShooterGameThread thread = (SpeedShooterGameThread) getThread();
if (thread.isRunning()) {
return thread.recieveTouch(event);
} else {
return false;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.