本文實例講述了Android編程使用GestureDetector實現簡單手勢監聽與處理的方法。分享給大家供大家參考,具體如下:
添加手勢識別監聽步驟:
一、給相應的控件添加觸摸監聽事件,
二、利用GestureDetector轉發這個觸摸事件。
三、事先定義好一個實現simpleongestureListener這個監聽的接口的類
四、在這個監聽中處理各種事件。
具體代碼如下:
MainActivity代碼如下:
package com.example.gesturedetector; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { ImageView img; GestureDetector myGestureDetector; class myGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (e1.getX()-e2.getX()>50) { Toast.makeText(MainActivity.this,"從右往左滑動",Toast.LENGTH_LONG).show(); }else if(e2.getX()-e1.getX()>50){ Toast.makeText(MainActivity.this,"從左往右滑動",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); img = (ImageView) findViewById(R.id.img); myGestureDetector = new GestureDetector(new myGestureListener()); img.setOnTouchListener(new View.OnTouchListener() { //motionEvent可以捕捉我們觸摸屏幕的event事件 @Override public boolean onTouch(View view, MotionEvent motionEvent) { myGestureDetector.onTouchEvent(motionEvent); return true; } }); } }
activity_main的代碼如下:
<?xml version="1.0" encoding="utf-8"?> <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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.gesturedetector.MainActivity"> <ImageView android:id="@+id/img" android:src="@mipmap/ic_launcher" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
更多關于Android相關內容感興趣的讀者可查看本站專題:《Android手勢操作技巧匯總》、《Android基本組件用法總結》、《Android開發入門與進階教程》、《Android調試技巧與常見問題解決方法匯總》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。