使用ViewFlipper控件实现图片切换
前言
ViewFlipper是一个切换控件
1、一般用于图片的切换
2、也可以用来添加View,不限定只用于ImageView,也可以是自定义View;只是我们经常利用ViewFlipper来实现ImageView的切换,如果切换自定义的View,使用ViewPager做更方便吧。
一、使用ViewFlipper实现「图片切换」demo案例
ViewFlipper布局:
<ViewFlipper
android:id="@+id/flipper"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginTop="10dp"
android:flipInterval="2000" />
代码实现:
ViewFlipper mFlipper = findViewById(R.id.flipper);
mFlipper.addView(getImageView(R.mipmap.img_1));
mFlipper.addView(getImageView(R.mipmap.img_2));
mFlipper.addView(getImageView(R.mipmap.img_3));
mFlipper.addView(getImageView(R.mipmap.img_4));
if (mFlipper.getChildCount() > 1) {
mFlipper.startFlipping();
} else {
mFlipper.stopFlipping();
}
二、完整版demo「包含手势检测,可以手动滑动图片切换」
代码实现:
/**
* 图片切换demo:手势切换
*/
public class TwoActivity extends Activity {
private ViewFlipper mFlipper;
private GestureDetector mDetector; //手势检测
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
initView();
initData();
initAction();
}
private void initView() {
mFlipper = findViewById(R.id.flipper);
mDetector = new GestureDetector(new simpleGestureListener());
}
private void initData() {
mFlipper.addView(getImageView(R.mipmap.img_1));
mFlipper.addView(getImageView(R.mipmap.img_2));
mFlipper.addView(getImageView(R.mipmap.img_3));
mFlipper.addView(getImageView(R.mipmap.img_4));
}
@SuppressLint("ClickableViewAccessibility")
private void initAction() {
mFlipper.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return mDetector.onTouchEvent(motionEvent);//手势监听
}
});
if (mFlipper.getChildCount() > 1) {
mFlipper.startFlipping();
} else {
mFlipper.stopFlipping();
}
}
private ImageView getImageView(int id) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(id);
return imageView;
}
private class simpleGestureListener extends GestureDetector.SimpleOnGestureListener {
final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 200;
//不知道为什么,不加上onDown函数的话,onFling就不会响应,真是奇怪
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// Fling left
if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
mFlipper.showNext();//展示下一张图片
Toast.makeText(TwoActivity.this, "Fling Left", Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
// Fling right
mFlipper.showPrevious();//展示上一张图片
Toast.makeText(TwoActivity.this, "Fling Right", Toast.LENGTH_SHORT).show();
}
return true;
}
}
}