温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android GestureDetector实现手势滑动效果

发布时间:2020-08-31 09:27:32 来源:脚本之家 阅读:162 作者:Vivinia_Vivinia 栏目:移动开发

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI