标签:
目标效果:
程序运行,手指在屏幕上从左往右或者从右往左滑动超过一定距离,就会吐司输出滑动方向和距离。
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>
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; } }); } }
标签:
原文地址:http://blog.csdn.net/hester_hester/article/details/51354728