Android GestureDetector实现手势滑动效果

发布时间:2019-08-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Android GestureDetector实现手势滑动效果脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例为大家分享了AndROId Gesturedetector实现手势滑动的具体代码,供大家参考,具体内容如下

目标效果:

  Android GestureDetector实现手势滑动效果

程序运行,手指在屏幕上从左往右或者从右往左滑动超过一定距离,就会吐司输出滑动方向和距离。

1.activITy_main.XMl页面放置一个ImageView控件。

activity_main.xML页面:

 <RelativeLayout xmlns:android="http://schemas.android.COM/apk/res/android"   xmlns:tools="http://schemas.android.com/tools"   android:layout_width="match_parent"   android:layout_height="match_parent"   tools:context=".MainActivity" >     <ImageView     android:id="@+id/ivShow"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:src="@drawable/ic_launcher" />   </RelativeLayout>

2.MainActivity.java页面实现滑动方法。

MainActivity.java页面:

 package com.example.gesturedetector;   import android.os.Bundle; import android.app.Activity; import android.util.LOG; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import android.widget.Toast;   public class MainActivity extends Activity {    PRivate ImageView ivShow;  private GestureDetector gestureDetector;    class myGestureListener extends SimpleOnGestureListener{  @override  /*识别滑动,第一个参数为刚开始事件,第二个参数为结束事件*/  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,   float velocityy) {   if(e1.getX()-e2.getX()>50){   Toast.makeText(MainActivity.this,"从右往左滑动"+(e1.getX()-e2.getX()),Toast.LENGTH_LONG).show();   }else if(e2.getX()-e1.getX()>50){   Toast.makeText(MainActivity.this,"从左往右滑动"+(e2.getX()-e1.getX()),Toast.LENGTH_LONG).show();   }   return suPEr.onFling(e1, e2, velocityX, velocityY);  }  }  @Override  protected void onCreate(Bundle savedInstancestate) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);    gestureDetector=new GestureDetector(MainActivity.this,new myGestureListener());    ivShow=(ImageView) findViewById(R.id.ivShow);  ivShow.setLongClickable(true); //view必须设置为true,否则手势识别无法正确工作  ivShow.setOnTouchListener(new OnTouchListener() {        /*可以捕获到触摸屏幕发生的Event事件*/   @Override   public boolean onTouch(View arg0, MotionEvent event) {   gestureDetector.onTouchEvent(event);//转发   return false;   }  });  } }

3.程序较简单,运行就可以显示目标效果了。

android教程
脚本网站
android studio

脚本宝典总结

以上是脚本宝典为你收集整理的Android GestureDetector实现手势滑动效果全部内容,希望文章能够帮你解决Android GestureDetector实现手势滑动效果所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。