首页 > 系统 > Android > 正文

Android GestureDetector实现手势滑动效果

2019-12-12 00:11:18
字体:
来源:转载
供稿:网友

本文实例为大家分享了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.程序较简单,运行就可以显示目标效果了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表