参考:https://blog.csdn.net/u013378580/article/details/52038255
ViewFlipper组件继承了ViewAnimator,它可以调用addView(View v)添加组件,一旦向ViewFlipper添加了多个组件之后,ViewFlipper就可使用动画控制多个组件之间的切换。
效果图:
实现
1,布局的定义
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ViewFlipper
android:id="@+id/filpper"
android:layout_width="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_height="wrap_content"
android:autoStart="true"
android:flipInterval="2000"
android:inAnimation="@anim/anim_come_in"
android:outAnimation="@anim/anim_come_out"/>
</android.support.constraint.ConstraintLayout>
layout_custom.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
app:layout_constraintLeft_toLeftOf="parent"
android:layout_width="0dp"
app:layout_constraintRight_toLeftOf="@id/tv"
android:layout_height="50dp"
android:id="@+id/iv"
app:layout_constraintHorizontal_weight="1" />
<TextView
android:layout_width="0dp"
android:text="182*******2132"
android:gravity="center"
android:textSize="20sp"
app:layout_constraintLeft_toRightOf="@id/iv"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:id="@+id/tv"
android:layout_height="50dp"
app:layout_constraintHorizontal_weight="3" />
</android.support.constraint.ConstraintLayout>
2,定义动画
anim_come_in
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="1000"
android:fromYDelta="100%p"
android:toYDelta="0" />
</set>
anim_come_out
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="1000"
android:fromYDelta="0"
android:toYDelta="-100%p" />
</set>
3,Java代码
ViewFlipper viewFlipper= (ViewFlipper) findViewById(R.id.filpper);
int[] images = {R.drawable.a1,R.drawable.a2,R.drawable.a3};
for (int i = 0; i < 500; i++) {
View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_custom, null);
view.findViewById(R.id.iv).setBackgroundResource(images[i % images.length]);
viewFlipper.addView(view);
}