Android中的手势切换——使用ViewFlipper

首先在layout的xml文件中定义一个ViewFlipper:

 

 

声明一个新的GestureDetector,重写它的onFling()函数,在这个函数里面判断手势,这里为横向的拖动:

public class MyGestureDetector extends SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) { return false; } if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { viewFlipper.setInAnimation(slideLeftIn); viewFlipper.setOutAnimation(slideLeftOut); viewFlipper.showNext(); } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { viewFlipper.setInAnimation(slideRightIn); viewFlipper.setOutAnimation(slideRightOut); viewFlipper.showPrevious(); } } catch (Exception e) { } return false; } } 

 

注意在Activity中重写onTouchEvent()函数:

private ViewFlipper viewFlipper; private Animation slideLeftIn; private Animation slideLeftOut; private Animation slideRightIn; private Animation slideRightOut; private GestureDetector gestureDetector; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); viewFlipper = (ViewFlipper)findViewById(R.id.viewFlipper); slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in); slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out); slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in); slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out); gestureDetector = new GestureDetector(new MyGestureDetector()); new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; } @Override public boolean onTouchEvent(MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } else { return false; } } 

 

最后,在res文件夹下新建一个anim文件夹,用来存放view之间切换的动画文件:

1.slide_left_in.xml

 

2.slide_left_out.xml

 

3.slide_right_in.xml

 

4.slide_right_out.xml

 

 

运行即可见效果~

你可能感兴趣的:(Android相关)