MainActivity :
public class MainActivity extends Activity {
GestureDetector myGestureDetector;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
myGestureDetector = new GestureDetector(new myGestureLister());
iv.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
myGestureDetector.onTouchEvent(event);
return true;
}
});
}
class myGestureLister extends 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);
}
}
}
佈局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#555"/>
</RelativeLayout>