ViewFlipper实现简单手势操作
扫描二维码
随时随地手机看文章
package com.example.administrator.viewflipper; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.ViewFlipper; public class MainActivity extends ActionBarActivity { private ViewFlipper viewFlipper; private int[] resId = new int[]{R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4}; private float startX; private enum directions{LEFT,RIGHT,NULL}; private directions slip_direction; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewFlipper = (ViewFlipper)findViewById(R.id.flipper); for (int i = 0 ; i < resId.length ; ++i){ viewFlipper.addView(getImage(resId[i])); } //自动播放 // viewFlipper.setInAnimation(this,R.anim.left_in); // viewFlipper.setOutAnimation(this, R.anim.left_out); // viewFlipper.setFlipInterval(3000); // viewFlipper.startFlipping(); } /** * 简单的手势操作 * @param event * @return */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: startX = event.getX(); slip_direction = directions.NULL; break; case MotionEvent.ACTION_MOVE: //向右滑 if(event.getX() - startX > 100){ slip_direction = directions.RIGHT; } //向左滑 if(startX - event.getX() > 100){ slip_direction = directions.LEFT; } break; case MotionEvent.ACTION_UP: switch (slip_direction){ case LEFT: if(viewFlipper.isFlipping()){ viewFlipper.stopFlipping(); } viewFlipper.setInAnimation(this,R.anim.right_in); viewFlipper.setOutAnimation(this, R.anim.right_out); viewFlipper.showPrevious(); break; case RIGHT: if(viewFlipper.isFlipping()){ viewFlipper.stopFlipping(); } viewFlipper.setInAnimation(this, R.anim.left_in); viewFlipper.setOutAnimation(this, R.anim.left_out); viewFlipper.showNext(); break; case NULL: break; } break; } return super.onTouchEvent(event); } private ImageView getImage(int resId){ ImageView img = new ImageView(this); img.setImageResource(resId); return img; } }