使用手势模拟左右滑动

"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.androiddemoset.MainActivity" >

    "#000000"
        android:layout_centerInParent="true"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:textColor="#ffffff"
        android:text="@string/hello_world"
        android:id="@+id/tv"
        android:gravity="center" />

</RelativeLayout>
package com.example.androiddemoset;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity  implements OnTouchListener{

    private GestureDetector detector;
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        detector=new GestureDetector(this, new MyListener());
        tv=(TextView)findViewById(R.id.tv);
        tv.setClickable(true);
        tv.setOnTouchListener(this);
    }

     private class MyListener extends SimpleOnGestureListener{
         @Override// e1: 第一个MotionEvent_DOWN事件   e2: 最后的MotionEvent_UP事件
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
             //触发条件:滑动距离大于50像素,水平移动速度大于50像素/秒
             int min_fling_distance=50;
             int min_velocityX=100;
             //判断左滑事件
             if(e1.getX()-e2.getX()>min_fling_distance&&Math.abs(velocityY)>min_velocityX){
                 Log.e("onFling", "左滑");
             }
             //判断右滑事件
             if(e2.getX()-e1.getX()>min_fling_distance&&Math.abs(velocityX)>min_velocityX){
                 Log.e("onFling", "右滑");
             }
            return super.onFling(e1, e2, velocityX, velocityY);
        }
     }

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {
        return detector.onTouchEvent(arg1);
    }

}

你可能感兴趣的:(Android手势)