Open In App

ViewSwitcher in Android with Example

Last Updated : 25 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

All android apps will have a feature to switch different views in order to explain/promote their site or product. Visual representation of a product by showing different views will impress the customers easily. In this article, let us see how to bring the “ViewSwitcher” to Android. ViewSwitcher is a sub-class of ViewAnimator and is used for switching between views which bring different views to customers. It is an element of the transition widget which helps us to add transitions on the views. We can use that to animate a view on the screen. ViewSwitcher switches smoothly also and even between two different views (i.e. TextView, ImageView, or any Layout) and because of this feature, one can impress customers by showing TextView, Imageview alternatively wherever required. In our example, let us see with ImageView itself.

Important Note: ViewSwitcher can only have two child views and that only one is shown at a time. If you have more than two child views in ViewSwitcher, java.lang.IllegalStateException of “Can’t add more than 2 views to a ViewSwitcher” error will come.

ViewSwitcher Initialization

Java




// We can initialize ViewSwitcher in the below way , where
// simpleViewSwitcher1
// is the id of ViewSwitcher in xml file. Usually xml file
// name will be
// activity_main but we can have meaningful name.
// let our xml file name be activity_viewswitcher
ViewSwitcher simpleViewSwitcher1 = (ViewSwitcher)findViewById(R.id.simpleViewSwitcher1);


 Let us see Important Methods Of ViewSwitcher, their functionality, and their code implementation

Important Methods

General methods and its description:

General Methods

Description

getNextView()

In order to return to the next view to be displayed in ViewSwitcher, 

the getNextView() method is used and it returns the view id of the 

next view to be displayed.

reset()

There may be a requirement to reset the ViewSwitcher on a click event 

and hence it behaves like the first-time animation has not yet played. 

reset() method is used for that.

showNext()

ViewSwitcher can have only 2 views. Only one view is shown at a time.

To show the next view, the required method is showNext()

showPrevious()

ViewSwitcher can have only 2 views. Only one view is shown at a time. 

To show the previous view, the required method is showPrevious()

Animation related methods: 

Animation Related Methods

Description

loadAnimation(Context context, int id)

This method is used whenever we need to define an object of 

Animation class through AnimationUtilities class by calling a 

static method loadAnimation.

setInAnimation(loadIn) In order to set the animation of the appearance of the object on the screen
setOutAnimation(out)

When we show the next view, first view has to be removed and 

that is done by using setOutAnimation()

setFactory(ViewFactory factory)

It is used to create a new view for ViewSwitcher. The old one is 

replaced and a new view is created by using this method.

Attributes of ViewSwitcher

By seeing the attributes along with methods that will help in the project. 

Attributes

Description

id To uniquely identify a ViewSwitcher.

padding

  • paddingRight
  • paddingLeft
  • paddingTop
  • paddingBottom
  • padding

This attribute is used to set the padding from the left, right, the top or bottom side of a ViewSwitcher

  • set the padding from the right side of a ViewSwitcher.
  • set the padding from the left side of a ViewSwitcher.
  • set the padding from the top side of a ViewSwitcher
  • set the padding from the bottom side of a ViewSwitcher.
  • set the padding from all the sides of a ViewSwitcher.
background

Set the background of a ViewSwitcher by this method. 

To make a pleasing appeal, the background has to be set.

We can set a color or a drawable in the background of a background:  

XML




<ViewSwitcher
android:id="@+id/simpleViewSwitcher1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp" 
android:background="#0F9D58">
<!-- set 20 dp padding from all the sides of ViewSwitcher
     set GFG specified color in the background of ViewSwitcher -->
 
<!-- Rest of view are here -- >
 
</ViewSwitcher>


We can set Background via  ViewSwitcher Java class:

Java




// set any color that you want
simpleViewSwitcher1.setBackgroundColor(Color.<Your favorite color>);


Example

A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

 

ViewSwitcher in Android

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML




<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <!-- ViewSwitcher with two views one is ImageView and other
         is LinearLayout in which we have a ImageView and a TextView -->
    <ViewSwitcher
        android:id="@+id/simpleViewSwitcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#0F9D58"
        android:padding="20dp">
 
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:src="@drawable/bir" />
 
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical">
 
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/bird" />
 
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical">
 
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/bird" />
 
        </LinearLayout>
 
    </ViewSwitcher>
 
 
    <Button
        android:id="@+id/buttonNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:background="#005"
        android:text="NEXT"
        android:textColor="#fff"
        android:textStyle="bold" />
 
    <Button
        android:id="@+id/buttonPrevious"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:background="#005"
        android:text="PREVIOUS"
        android:textColor="#fff"
        android:textStyle="bold" />
 
</LinearLayout>


Step 3: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ViewSwitcher;
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
 
    private ViewSwitcher simpleViewSwitcher;
    Button btnNext, btnPrev;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // get The references of Button and ViewSwitcher
        btnNext = (Button) findViewById(R.id.buttonNext);
        btnPrev = (Button) findViewById(R.id.buttonPrevious);
 
        // get the reference of ViewSwitcher
        simpleViewSwitcher = (ViewSwitcher) findViewById(R.id.simpleViewSwitcher);
         
        // Declare in and out animations and load them using AnimationUtils class
        Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
        Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
 
        // set the animation type to ViewSwitcher
        simpleViewSwitcher.setInAnimation(in);
        simpleViewSwitcher.setOutAnimation(out);
         
        // ClickListener for NEXT button
        // When clicked on Button ViewSwitcher will switch between views
        // The current view will go out and next view will come in with specified animation
        btnNext.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                // show the next view of ViewSwitcher
                simpleViewSwitcher.showNext();
            }
        });
 
        btnPrev.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                // show the previous view of ViewSwitcher
                simpleViewSwitcher.showPrevious();
            }
        });
    }
}


Output

On running the android code in android studio, we can able to get the output as shown in the attached video. This is a useful feature that is used across many android apps.
 

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads