這篇文章主要爲大家詳細介紹了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.程序較簡單,運行就可以顯示目標效果了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。