ScrollView和GestureDetector触屏事件冲突

来源:互联网 发布:ubuntu安装vim完整版 编辑:程序博客网 时间:2024/06/05 01:06

当我们使用GestureDetector手势识别当前的动作并作相关的功能的时候,会发现如果当前的页面包含有滚动条或者listview的时候,GestureDetector中的onFling等。一些的方法不能正常的使用,或者是在一个activity的有些部位可以使用而其他的就不行。

下面给一个解决办法,之所以会出现上述的情况网上说是因为ScrollView等一些控件抢占了MotionEvent 事件,才会出现一些了的问题,因此我们使用dispatchTouchEvent事件重新分发一下就行,下面是代码。

@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {// TODO Auto-generated method stubmGestureDetector.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;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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() {@Overridepublic boolean onDown(MotionEvent e) {// TODO Auto-generated method stub// Toast.makeText(getApplicationContext(), "ondown",// Toast.LENGTH_SHORT).show();return true;}@Overridepublic boolean onFling(MotionEvent e1, MotionEvent e2,float velocityX, float velocityY) {// TODO Auto-generated method stubif (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();@Overridepublic boolean onTouchEvent(MotionEvent event) {// TODO Auto-generated method stubmGestureDetector.onTouchEvent(event);return super.onTouchEvent(event);}public void startActivityAndFinishSelf(Class<?> cls) {Intent intent = new Intent(this, cls);startActivity(intent);finish();}/* * 调用机制拦截 */@Overridepublic boolean dispatchTouchEvent(MotionEvent ev) {// TODO Auto-generated method stubmGestureDetector.onTouchEvent(ev);return super.dispatchTouchEvent(ev);}}


0 0
原创粉丝点击