当我们使用GestureDetector手势识别当前的动作并作相关的功能的时候,会发现如果当前的页面包含有滚动条或者listview的时候,GestureDetector中的onFling等。一些的方法不能正常的使用,或者是在一个activity的有些部位可以使用而其他的就不行。
下面给一个解决办法,之所以会出现上述的情况网上说是因为ScrollView等一些控件抢占了MotionEvent 事件,才会出现一些了的问题,因此我们使用dispatchTouchEvent事件重新分发一下就行,下面是代码。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
mGestureDetector.onTouchEvent(ev);
return super.dispatchTouchEvent(ev);
}
其中的
mGestureDetector是定义的GestureDetector对象;
下main是整个实现跳转的逻辑
package com.hit.wuxi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.Window;
import android.widget.Toast;
public abstract class BaseSetUpActivity extends Activity {
private SharedPreferences sp;
private GestureDetector mGestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
sp = getSharedPreferences("cpnfig", MODE_PRIVATE);
initView();
}
@SuppressWarnings("deprecation")
private void initView() {
// TODO Auto-generated method stub
// 初始化手势识别器
mGestureDetector = new GestureDetector(
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "ondown",
// Toast.LENGTH_SHORT).show();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// TODO Auto-generated method stub
if (Math.abs(velocityX) < 200) {
Toast.makeText(getApplicationContext(), "滑动的有点慢哦!",
Toast.LENGTH_SHORT).show();
return true;
}
if ((e2.getRawX() - e1.getRawX()) > 200) {
showPre();
overridePendingTransition(R.anim.pre_in,
R.anim.pre_out);// 加载动画
return true;
}
if ((e1.getRawX() - e2.getRawX()) > 200) {
showNext();
overridePendingTransition(R.anim.next_in,
R.anim.next_out);
return true;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
});
}
public abstract void showNext();
public abstract void showPre();
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
public void startActivityAndFinishSelf(Class<?> cls) {
Intent intent = new Intent(this, cls);
startActivity(intent);
finish();
}
/*
* 调用机制拦截
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
mGestureDetector.onTouchEvent(ev);
return super.dispatchTouchEvent(ev);
}
}