TextSwitcher Tutorial With Example In Android Studio

In Android, TextSwitcher is a specialized ViewSwitcher that contains only children of type TextView. TextSwitcher is available in Android from version Android 1.6+.

A TextSwitcher is useful to animate a label(i.e. text) on screen. It is an element of transition widget which helps us to add transitions on the labels. Whenever setText(CharSequence) method is called, TextSwitcher simply animates the current text out and new text in. For Example you need to cycle through information in a TextView like Navigating through a list of dates using Left and Right button.

TextSwitcher in Android


Steps For TextSwitcher Implementation:

New views in TextSwitcher is created using factory switcherid.setFactory(). And when setText() method is used, it first removes the old view using an animation set with the switcherid.setOutAnimation() method, and then places the new one using the animation set by the switcherid.setInAnimation() method.

  1. Get the reference of TextSwitcher in class using findViewById() method, or you can also create an object dynamically.
  2. Set a factory using switcherid.setFactory()
  3. Set an in-animation using switcherid.setInAnimation()
  4. Set an out-animation using switcherid.setOutAnimation()

Basic TextSwitcher XML Code:

<TextSwitcher
    android:id="@+id/simpleTextSwitcher"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

Important Methods Of TextSwitcher:

Let’s we discuss some important methods of TextSwitcher that may be called in order to manage the TextSwitcher.

1. setFactory(ViewFactory factory): This method is used to create a new view for TextSwitcher. By using this method we create a new TextView and replace the old view with that.

Below we show how to create a new view using setFactory method.

TextSwitcher simpleTextSwitcher=(TextSwitcher)findViewById(R.id. simpleTextSwitcher); // get reference of TextSwitcher

// Set the ViewFactory of the TextSwitcher that will create TextView object when asked
simpleTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

public View makeView() {
// TODO Auto-generated method stub
// create a TextView
TextView t = new TextView(MainActivity.this);
// set the gravity of text to top and center horizontal
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
// set displayed text size
t.setTextSize(36);
return t;
}
});

2. setCurrentText(CharSequence text): This method is used to set the text on the TextView that is currently showing.

Below we set the Text in a TextView that is currently showing.

TextSwitcher simpleTextSwitcher = (TextSwitcher) findViewById(R.id.simpleTextSwitcher); // get the reference of TextSwitcher
simpleTextSwitcher.setCurrentText("current Text"); // set current text in TextView that is currently showing

setCurrentText in TextSwitcher Android

3. setText(CharSequence text): This method is used to set the text on the next view and switches to the next view.

Below we set the Text on next view and switch to next view.

TextSwitcher simpleTextSwitcher = (TextSwitcher) findViewById(R.id.simpleTextSwitcher); // get the reference of TextSwitcher
simpleTextSwitcher.setText("text after switching"); // set current text on the next view and switch to next view

setText in TextSwitcher Android

4. loadAnimation(Context context, int id): This method is used whenever we need to define an object of Animation class through AnimationUtils class by calling a static method loadAnimation.

Below we create an object of Animation class and load an animation by using AnimationUtils class.

// load an animation by 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);

5. setInAnimation(Animation inAnimation): This method is used to set the animation of the appearance of the object on the screen.

Below we create an object of Animation class and load an animation by using AnimationUtils class and then set the Animation on TextSwitcher.

TextSwitcher simpleTextSwitcher=(TextSwitcher)findViewById(R.id. simpleTextSwitcher); // initiate a TextSwitcher
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left); // load an animation
simpleTextSwitcher.setInAnimation(in); // set in Animation for TextSwitcher

setInAnimation in TextSwitcher Android

6. setOutAnimation(Animation outAnimation): This method does the opposite of setInAnimation().

Whenever we set a new label in TextView, it first removes the old view using an animation set with the setOutAnimation() method, and then places the new one using the animation set by the setInAnimation() method.

Below we create an object of Animation class and load an animation by using AnimationUtils class and then set the out Animation on TextSwitcher

TextSwitcher simpleTextSwitcher=(TextSwitcher)findViewById(R.id. simpleTextSwitcher); // get reference of TextSwitcher
Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right); // load an animation
simpleTextSwitcher.setOutAnimation(out); // set out Animation for TextSwitcher

setOutAnimation in TextSwitcher Android


Attributes of TextSwitcher:

Now let’s we discuss some common attributes of TextSwitcher that helps us to configure it in our layout (xml).

1. Id: id attribute is used to uniquely identify a TextSwitcher.

Below we set the id of the TextSwitcher that is used to uniquely identify it.

<TextSwitcher
android:id="@+id/simpleTextSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content" /><!--  id of TextSwitcher that is used to uniquely identify it -->

2. padding: This attribute is used to set the padding from left, right, top or bottom side of a TextSwitcher.

  • paddingRight: This attribute is used to set the padding from the right side of a TextSwitcher.
  • paddingLeft: This attribute is used to set the padding from the left side of a TextSwitcher.
  • paddingTop: This attribute is used to set the padding from the top side of a TextSwitcher.
  • paddingBottom: This attribute is used to set the padding from the bottom side of a TextSwitcher.
  • Padding: This attribute is used to set the padding from the all the side’s of a TextSwitcher.

Below we set the 10dp padding from all the sides of a TextSwitcher

<TextSwitcher
    android:id="@+id/simpleTextSwitcher"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="50dp"
    android:background="#028B2F"
    android:padding="20dp"/><!--Setting background and padding in TextSwitcher-->

background padding in TextSwitcher Android

3. background: This attribute is used to set the background of a TextSwitcher. We can set a color or a drawable in the background of a TextSwitcher.

In the code of padding we also used background and few other common attribute.

Setting background In TextSwitcher In Java class:

TextSwitcher simpleTextSwitcher = (TextSwitcher) findViewById(R.id.simpleTextSwitcher); // get the reference of TextSwitcher.
simpleTextSwitcher.setBackgroundColor(Color.BLACK); // set black color in the background of TextSwitcher.

TextSwitcher Example In Android Studio:

Below is the example of TextSwitcher in which we display a TextSwitcher by using its different attributes. In this we use one Button for changing the label of TextSwitcher. Firstly we create a string array and create dynamic TextView using setFactory method and then load and set slide in left and slide in right animation and finally set the text in the TextSwitcher on button click using setText method. Whenever a user click on next button TextSwitcher switch between the labels and the current label will go out and next label will come in with specified animation.

Below you can download complete Android Studio code, see final output and step by step explanation of the example:

Download Code (Password: abhiandroid) ?

TextSwitcher Example In Android Studio

Step 1: Create a new project and name it TextSwitcherExample

Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code :

In this step we open an xml file and add the code for displaying a Button and a TextSwitcher by using its different attributes.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">


<TextSwitcher
android:id="@+id/simpleTextSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp" />


<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_gravity="center"
android:background="#005"
android:textColor="#fff"
android:textStyle="bold"
android:text="NEXT" />

</LinearLayout>

Step 3: Open src -> package -> MainActivity.java

In this step we open MainActivity and add the code to initiate the TextSwitcher and Button. Here firstly we create an string array and create dynamic TextView using setFactory method and then load and set slide in left and slide in right animation and finally set the text in the TextSwitcher on button click using setText method. Whenever a user click on next button TextSwitcher switch between the labels and the current label will go out and next label will come in with specified animation.

package com.example.ip_d.textswitcherexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class MainActivity extends AppCompatActivity {
    private TextSwitcher simpleTextSwitcher;
    Button btnNext;


    // Array of String to Show In TextSwitcher
    String strings[] = {"Text Switcher 1", "Text Switcher 2", "Text Switcher 3", "Text Switcher 4", "Text Switcher 5"};
    int messageCount = strings.length;
    // to keep current Index of textID array
    int currentIndex = -1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // get The references if Button and TextSwitcher
        btnNext = (Button) findViewById(R.id.buttonNext);
        simpleTextSwitcher = (TextSwitcher) findViewById(R.id.simpleTextSwitcher);
        // Set the ViewFactory of the TextSwitcher that will create TextView object when asked
        simpleTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

            public View makeView() {
                // TODO Auto-generated method stub
                // create a TextView
                TextView t = new TextView(MainActivity.this);
                // set the gravity of text to top and center horizontal
                t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
                // set displayed text size
                t.setTextSize(36);
                return t;
            }
        });

        // 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 TextSwitcher
        simpleTextSwitcher.setInAnimation(in);
        simpleTextSwitcher.setOutAnimation(out);

            //text appear on start
        simpleTextSwitcher.setCurrentText("click on next button to switch text");
        // ClickListener for NEXT button
        // When clicked on Button TextSwitcher will switch between labels
        // The current label will go out and next label will come in with specified animation
        btnNext.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                currentIndex++;
                // If index reaches maximum then reset it
                if (currentIndex == messageCount)
                    currentIndex = 0;
                simpleTextSwitcher.setText(strings[currentIndex]); // set Text in TextSwitcher
            }
        });

    }

}

Output:

Now run the App and you will see TextSwitcher in action. Simply click on Next button and text will start switching one to another.

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!

One thought on “TextSwitcher Tutorial With Example In Android Studio”

Leave a Reply

Your email address will not be published. Required fields are marked *



Continue Reading:
Android Developer Money eBook
One More Step...

Enter your email and I'll send you a FREE copy of Android Dev Dollaring eBook:
Send Me This eBook >>
We hate SPAM and promise to keep your email address safe.
close-link




One More Step...

Enter your email and I'll send you a FREE copy of Android Dev Dollaring eBook:
Send Me This eBook >>
We hate SPAM and promise to keep your email address safe.
close-link

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!

Join over 5256 Android developers in our community and get access to this free eBook now!
close-link

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

DOWNLOAD THIS FREE eBook!

This free eBook will help you master the learning of Android App Development in Android Studio!
close-link

Struggling to learn Android App Development?

Download this FREE eBook to master learning of Android App Development!
close-link