ViewFlipper組件繼承ViewAnimator,可調用addView(View v)添加多個組件,一旦向ViewFlipper中添加了多個組件以後,ViewFlipper就可以使用動畫控制多個組件之間的切換效果。android
下面是個實例,自動播放的圖片庫app
佈局文件以下ide
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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/details" android:layout_width="match_parent" android:layout_height="match_parent" android:flipInterval="1000">
<ImageView android:src="@drawable/school1" android:layout_width="match_parent" android:layout_height="wrap_content"/>
<ImageView android:src="@drawable/school2" android:layout_width="match_parent" android:layout_height="wrap_content"/>
<ImageView android:src="@drawable/school3" android:layout_width="match_parent" android:layout_height="wrap_content"/>
</ViewFlipper>
<Button android:id="@+id/btn1" android:text="<" android:onClick="prev" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@+id/btn2" app:layout_constraintStart_toStartOf="@+id/btn1" android:onClick="auto" android:text="自動播放"/>
<Button android:id="@+id/btn2" android:text=">" android:onClick="next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
主程序代碼以下佈局
public class MainActivity extends AppCompatActivity { private ViewFlipper viewFlipper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewFlipper = findViewById(R.id.details); } public void prev(View source) { viewFlipper.setInAnimation(this, R.anim.slide_in_right); viewFlipper.setOutAnimation(this,R.anim.slide_out_left); //顯示上一個組件
viewFlipper.showPrevious(); //中止自動播放
viewFlipper.stopFlipping(); } public void next(View source) { viewFlipper.setInAnimation(this, android.R.anim.slide_in_left); viewFlipper.setOutAnimation(this, android.R.anim.slide_out_right); //顯示上一個組件
viewFlipper.showNext(); //中止自動播放
viewFlipper.stopFlipping(); } public void auto(View source) { viewFlipper.setInAnimation(this, android.R.anim.slide_in_left); viewFlipper.setOutAnimation(this, android.R.anim.slide_out_right); //開始自動播放
viewFlipper.startFlipping(); } }
運行結果以下動畫