1. 简单应用
ViewFlipper
继承ViewAnimator
,用于视图的轮播。
android:flipInterval
指定轮播间隔时间android:autoStart
是否自动开始轮播android:inAnimation
指定进入时动画android:outAnimation
指定退出时动画
资源文件
<ViewFlipper
android:layout_width="match_parent"
android:layout_height="200dp"
android:flipInterval="2000"
android:autoStart="true"
android:inAnimation="@anim/anim_enter_from_bottom"
android:outAnimation="@anim/anim_exit_to_top">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/switcher1"
android:scaleType="fitXY"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/switcher2"
android:scaleType="fitXY"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/switcher3"
android:scaleType="fitXY"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/switcher4"
android:scaleType="fitXY"/>
</ViewFlipper>
进入动画anim_enter_from_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%"
android:toYDelta="0"
android:duration="1000" />
退出动画anim_exit_to_top.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:toYDelta="-100%"
android:duration="1000" />
效果如下
2. 主要方法
startFlipping()
用于手动开始轮播,而stopFlipping()
则停止轮播。
showNext()
和showPrevious()
显示视图的切换。
// 显示上一个视图
private void previous() {
mViewFlipper.stopFlipping();
mViewFlipper.setInAnimation(this, R.anim.anim_enter_from_top);
mViewFlipper.setOutAnimation(this, R.anim.anim_exit_to_bottom);
mViewFlipper.showPrevious();
}
// 手动开始轮播
private void play() {
mViewFlipper.setInAnimation(this, R.anim.anim_enter_from_bottom);
mViewFlipper.setOutAnimation(this, R.anim.anim_exit_to_top);
mViewFlipper.startFlipping();
}
// 显示下一个视图
private void next() {
mViewFlipper.stopFlipping();
mViewFlipper.setInAnimation(this, R.anim.anim_enter_from_bottom);
mViewFlipper.setOutAnimation(this, R.anim.anim_exit_to_top);
mViewFlipper.showNext();
}
进入动画anim_enter_from_top.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="-100%"
android:toYDelta="0"
android:duration="1000" />
退出动画anim_exit_to_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:toYDelta="100%" />
效果如下