您好,登錄后才能下訂單哦!
import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.util.Log; import android.widget.RelativeLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//這里的xml是一個空白的layout //需要監聽左右滑動事件的view RelativeLayout view = (RelativeLayout) this.findViewById(R.id.layout); //setLongClickable是必須的 view.setLongClickable(true); view.setOnTouchListener(new MyGestureListener(this)); } /** * 繼承GestureListener,重寫left和right方法 */ private class MyGestureListener extends GestureListener { public MyGestureListener(Context context) { super(context); } @Override public boolean left() { Log.e("test", "向左滑"); return super.left(); } @Override public boolean right() { Log.e("test", "向右滑"); return super.right(); } } } import android.content.Context; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.GestureDetector; import android.view.View; import android.view.View.OnTouchListener; import android.view.MotionEvent; /** * 實現監聽左右滑動的事件,哪個view需要的時候直接setOnTouchListener就可以用了 * @author LinZhiquan * */ public class GestureListener extends SimpleOnGestureListener implements OnTouchListener { /** 左右滑動的最短距離 */ private int distance = 100; /** 左右滑動的最大速度 */ private int velocity = 200; private GestureDetector gestureDetector; public GestureListener(Context context) { super(); gestureDetector = new GestureDetector(context, this); } /** * 向左滑的時候調用的方法,子類應該重寫 * @return */ public boolean left() { return false; } /** * 向右滑的時候調用的方法,子類應該重寫 * @return */ public boolean right() { return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // TODO Auto-generated method stub // e1:第1個ACTION_DOWN MotionEvent // e2:最后一個ACTION_MOVE MotionEvent // velocityX:X軸上的移動速度(像素/秒) // velocityY:Y軸上的移動速度(像素/秒) // 向左滑 if (e1.getX() - e2.getX() > distance && Math.abs(velocityX) > velocity) { left(); } // 向右滑 if (e2.getX() - e1.getX() > distance && Math.abs(velocityX) > velocity) { right(); } return false; } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub gestureDetector.onTouchEvent(event); return false; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public int getVelocity() { return velocity; } public void setVelocity(int velocity) { this.velocity = velocity; } public GestureDetector getGestureDetector() { return gestureDetector; } public void setGestureDetector(GestureDetector gestureDetector) { this.gestureDetector = gestureDetector; } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。