温馨提示×

温馨提示×

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

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

Android中怎么利用GestureDetector实现手势滑动效果

发布时间:2021-08-11 13:53:38 来源:亿速云 阅读:111 作者:Leah 栏目:编程语言

这篇文章给大家介绍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;  } }); }}

关于Android中怎么利用GestureDetector实现手势滑动效果就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

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

AI