Android通过手势实现翻页效果

布局使用ViewFlipper装载图片,并通过showPrevious()和showNext()方法展示图片的上一页/下一页,布局文件如下:


    

编写一个ChangePage的Activity实现OnGestureListener接口,在onFling()方法中编写核心的图片切换代码,通过ViewFlipper更换图片,还可以通过ViewFlipper的setInAnimation和setOutAnimation方法给图片切换设置切换动画,代码如下:

public class ChangePage extends Activity implements GestureDetector.OnGestureListener{
    GestureDetector detector;
    ViewFlipper flipper;
    Animation animation[];
    final int MINIMUM_DISTANCE = 50;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.flipper);
        detector = new GestureDetector(this,this);
        flipper = (ViewFlipper) findViewById(R.id.flipper);
        flipper.addView(addImageView(R.drawable.one));
        flipper.addView(addImageView(R.drawable.two));
        flipper.addView(addImageView(R.drawable.three));
        flipper.addView(addImageView(R.drawable.four));
        flipper.addView(addImageView(R.drawable.five));
        loadAnimation();

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return detector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if(e2.getX()-e1.getX() > MINIMUM_DISTANCE){
            flipper.setInAnimation(animation[0]);
            flipper.setOutAnimation(animation[1]);
            flipper.showPrevious();
            return true;
        }else if(e1.getX() - e2.getX() > MINIMUM_DISTANCE){
            flipper.setInAnimation(animation[2]);
            flipper.setOutAnimation(animation[3]);
            flipper.showNext();
            return false;
        }
        return false;
    }
    private ImageView addImageView(int resId){
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(resId);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        return imageView;
    }

    private Animation[] loadAnimation(){
        animation = new Animation[4];
        animation[0] = AnimationUtils.loadAnimation(this,R.anim.left_in);
        animation[1] = AnimationUtils.loadAnimation(this,R.anim.right_out);
        animation[2] = AnimationUtils.loadAnimation(this,R.anim.right_in);
        animation[3] = AnimationUtils.loadAnimation(this,R.anim.left_out);
        return animation;
    }
}
注:加载动画代码为:Animation animation = AnimationUtils.loadAnimation(context,R.anim.xx);



你可能感兴趣的:(android)