Quick Tip: Android ViewFlipper Jump/Move/Switch To a Certain Child View

At times you might want to jump the user to a specific View inside a ViewFlipper on the click of some other View or some such scenario. So let’s say we have a ViewFlipper in our layout resource like this:

[xml]
<ViewFlipper
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewFlipper"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/first">

<!– more views –>

</LinearLayout>

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/second">

<!– more views –>

</LinearLayout>

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/third">

<!– more views –>

</LinearLayout>
</ViewFlipper>
[/xml]

When the Activity loads (is created) it instantiates the ViewFlipper and shows up the first child View (LinearLayout with the ID of first). If we want to programatically move/switch to a particular view position which is not the next one, in this case the third one then all we have to do is this:

[java]
ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
// 2 is the index for the 3rd child
viewFlipper.setDisplayedChild(2);
// or when you don’t know the index but the ID of the view
viewFlipper.setDisplayedChild( viewFlipper.indexOfChild(findViewById(R.id.third)) );
[/java]

Hope that helps!

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.