Simple usage of Android ViewFlipper

The ViewFlipper in Android is a layout container that can be used to achieve a view switching effect. It can display multiple views and offers methods to switch between them.

Here is a simple example of using ViewFlipper:

  1. Add ViewFlipper to the XML layout file.
<ViewFlipper
    android:id="@+id/viewFlipper"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="View 1" />
        
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="View 2" />

</ViewFlipper>
  1. In the Java code, locate the ViewFlipper and set the animation effect.
ViewFlipper viewFlipper = findViewById(R.id.viewFlipper);
viewFlipper.setInAnimation(this, android.R.anim.slide_in_left);
viewFlipper.setOutAnimation(this, android.R.anim.slide_out_right);
  1. Switch view:
viewFlipper.showNext(); // 显示下一个视图
viewFlipper.showPrevious(); // 显示上一个视图

Please note that viewFlipper.showNext() will display the next view and, if the current view is already the last one, it will return to the first view. Similarly, viewFlipper.showPrevious() will display the previous view and, if the current view is already the first one, it will return to the last view.

These are the steps for performing simple view switching using ViewFlipper. You can customize views and switching animations as needed to achieve more complex view switching effects.

bannerAds