1. 用作两个View切换,布局如下:
<ViewSwitcher
android:id="@+id/viewSwitcher"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/test1"
android:text="AAAAA"
android:gravity="center"
android:textSize="66sp"
android:background="@color/purple_200"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/test2"
android:text="BBBBB"
android:gravity="center"
android:textSize="66sp"
android:background="@color/teal_200"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ViewSwitcher>
2. 控制两个View的切换
if (viewSwitcher.getCurrentView() != test1) {
viewSwitcher.showNext();
}else {
viewSwitcher.showPrevious();
}
3. 添加切换动画
TranslateAnimation inAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f,
Animation.ABSOLUTE, 1.0f, Animation.ABSOLUTE, 1.0f);
inAnimation.setDuration(300);
viewSwitcher.setInAnimation(inAnimation);
TranslateAnimation outAnimation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1.0f,
Animation.ABSOLUTE, 1.0f, Animation.ABSOLUTE, 1.0f);
outAnimation.setDuration(300);
viewSwitcher.setOutAnimation(outAnimation);