use*_*977 6 android onclick touch touch-event
我希望能够在屏幕上的任何位置滑动以调用某个功能.但我也有Buttons,Linear Layouts因为我希望能够点击.如果我刷上Button我想 onInterceptTouchEvent给Intercept在调用Button的onTouchEvent和进行刷卡操作.如果我只是点击一个Button我不希望onInterceptTouchEvent被调用.相反,我希望Button的onTouchEvent要调用和执行Button click
但是当我尝试实现时,我会遇到错误onInterceptTouchEvent.
这是我的代码:
public class Game extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
//other code....
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
swipeScreen(); //if action recognized as swipe then swipe
break;
case MotionEvent.ACTION_MOVE:
float x = event.getX();
float y = event.getY();
float xDelta = Math.abs(x - mLastX);
float yDelta = Math.abs(y - mLastY);
if (yDelta > xDelta) {
return true;
}
break;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
ButtonOnClick(); //if not a swipe, then button click
return true;
}
Run Code Online (Sandbox Code Playgroud)
首先错误说: The method onInterceptTouchEvent(MotionEvent) of type Game must override or implement a supertype method
然后,而不是return true我将代码更改为:return super.onInterceptTouchEvent(event) 但后来我得到一个错误说:The method onInterceptTouchEvent(MotionEvent) is undefined for the type Activity
有人可以帮忙吗?
brn*_*nes 13
请注意,这onInterceptTouchEvent()是来自ViewGroup类的方法,而不是来自Activity.
您可以通过实现移动你的逻辑所期望的行为onInterceptTouchEvent()来dispatchTouchEvent(MotionEvent ev).记得调用超类实现dispatchTouchEvent(MotionEvent ev)来处理应该正常处理的事件.
另请注意,只有当delta大于触摸斜率的系统常量时,才应将移动视为滑动.我建议确保用户通过测试yDelta / 2 > xDelta而不是按照您想要的方向滑动yDelta > xDelta.
public class Game extends Activity {
private int mSlop;
private float mDownX;
private float mDownY;
private boolean mSwiping;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
ViewConfiguration vc = ViewConfiguration.get(this)
mSlop = vc.getScaledTouchSlop();
//other code....
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
mDownY = ev.getY();
mSwiping = false;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if(mSwiping) {
swipeScreen(); //if action recognized as swipe then swipe
}
break;
case MotionEvent.ACTION_MOVE:
float x = ev.getX();
float y = ev.getY();
float xDelta = Math.abs(x - mDownX);
float yDelta = Math.abs(y - mDownY);
if (yDelta > mSlop && yDelta / 2 > xDelta) {
mSwiping = true;
return true;
}
break;
}
return super.dispatchTouchEvent(ev);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10796 次 |
| 最近记录: |