Android入门之ViewFlipper翻转视图的使用详解

  package org.mk.android.demomanualflipper;

  import androidx.appcompat.app.AppCompatActivity;

  import android.content.Context;

  import android.os.Bundle;

  import android.view.GestureDetector;

  import android.view.MotionEvent;

  import android.widget.ImageView;

  import android.widget.ViewFlipper;

  public class MainActivity extends AppCompatActivity {

  private Context mContext;

  private ViewFlipper vflp_help;

  private int[] resId = {R.drawable.ad_pic_1, R.drawable.ad_pic_2,

  R.drawable.ad_pic_3, R.drawable.ad_pic_4, R.drawable.ad_pic_5};

  private final static int DISTANCE = 200; //最小距离

  private CustomerizedGestureListener cgListener;

  private GestureDetector gDetector;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  mContext = MainActivity.this;

  //实例化SimpleOnGestureListener与GestureDetector对象

  cgListener = new CustomerizedGestureListener();

  gDetector = new GestureDetector(this, cgListener);

  vflp_help = (ViewFlipper) findViewById(R.id.adFlipper);

  //动态导入添加子View

  for(int i = 0;i < resId.length;i++){

  vflp_help.addView(getImageView(resId[i]));

  }

  }

  //重写onTouchEvent触发MyGestureListener里的方法

  @Override

  public boolean onTouchEvent(MotionEvent event) {

  return gDetector.onTouchEvent(event);

  }

  //自定义一个GestureListener,这个是View类下的

  private class CustomerizedGestureListener extends GestureDetector.SimpleOnGestureListener {

  @Override

  public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {

  if(e1.getX() - e2.getX() > DISTANCE){

  vflp_help.setInAnimation(mContext,R.anim.right_in);

  vflp_help.setOutAnimation(mContext, R.anim.right_out);

  vflp_help.showNext();

  }else if(e2.getX() - e1.getX() > DISTANCE){

  vflp_help.setInAnimation(mContext,R.anim.left_in);

  vflp_help.setOutAnimation(mContext, R.anim.left_out);

  vflp_help.showPrevious();

  }

  return true;

  }

  }

  private ImageView getImageView(int resId){

  ImageView img = new ImageView(this);

  img.setBackgroundResource(resId);

  return img;

  }

  }