使用ViewFlipper实现图片轮播

使用ViewFlipper实现图片轮播_第1张图片

public class MainActivity extends AppCompatActivity {
    private ViewFlipper flipper;
    //背景图片int[] id
    private int[] resID = {R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        flipper = (ViewFlipper) findViewById(R.id.flipper);

        //动态导入的方式为ViewFlipper加入子View
        for(int i = 0; i < resID.length ; i++){
            flipper.addView(getimageview(resID[i]));
        }
        //为ViewFlipper去添加动画效果
        flipper.setInAnimation(this,R.anim.right_in);
        flipper.setOutAnimation(this,R.anim.right_out);
        //切换间隔时间
        flipper.setFlipInterval(3000);
        //开始播放
        flipper.startFlipping();
    }
    private ImageView getimageview(int resID){
        ImageView image = new ImageView(this);
        image.setBackgroundResource(resID);
        return image;
    }

  使用ViewFlipper实现图片轮播_第2张图片

手指滑动

public class MainActivity extends AppCompatActivity {
    private ViewFlipper flipper;
    //X横坐标
    private float startX;
    //背景图片int[] id
    private int[] resID = {R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        flipper = (ViewFlipper) findViewById(R.id.flipper);

        //动态导入的方式为ViewFlipper加入子View
        for(int i = 0; i < resID.length ; i++){
            flipper.addView(getimageview(resID[i]));
        }
    }
    private ImageView getimageview(int resID){
        ImageView image = new ImageView(this);
        image.setBackgroundResource(resID);
        return image;
    }

    //手指滑动
    @Override
    public boolean onTouchEvent(MotionEvent event) {
       switch (event.getAction()){
           case MotionEvent.ACTION_DOWN:{
               startX = event.getX();
               break;
           }
           case MotionEvent.ACTION_MOVE:{
               //向右滑动

               break;
           }
           case MotionEvent.ACTION_UP:{
               if(event.getX() - startX  > 100){
                   flipper.setInAnimation(this,R.anim.left_in);
                   flipper.setOutAnimation(this, R.anim.left_out);
                   flipper.showPrevious();                  //显示前一项
               }

               //向左滑动
               if(startX - event.getX() > 100){
                   flipper.setInAnimation(this,R.anim.right_in);
                   flipper.setOutAnimation(this,R.anim.right_out);
                   flipper.showNext();
               }
               break;
           }
       }

        return super.onTouchEvent(event);
    }

  

转载于:https://www.cnblogs.com/zmaibbs7/p/4854781.html

你可能感兴趣的:(使用ViewFlipper实现图片轮播)