Wednesday, November 20, 2024
Google search engine
HomeLanguagesJavaHow to Implement TextSwitcher in Android?

How to Implement TextSwitcher in Android?

In Android, TextSwitcher can be very useful for showcasing texts in an animated manner. TextSwitcher can be considered as a special version of ViewSwitcher. Its children are of TextView type only. TextSwitcher helps us to add transitions on the labels. Hence, it is an element of the transition widget. Whenever the setText(CharSequence) method is called, TextSwitcher quickly animates the current text out and new text in. This operation can be achieved by using both single and multiple buttons.  For a single button, we need to visit the array in a cyclic manner. In this article, we will be implementing TextSwitcher using it.

What We are Going to Build in this Article?

We will be building a simple application in which we will be implementing  TextSwitcher. After clicking on the Next button, we will notice that the text starts changing in a serial manner.

TextSwitcher is available in Android from version Android 1.6+.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextSwitcher
        android:id="@+id/textSwitcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:inAnimation="@anim/slide_in_right"
        android:outAnimation="@anim/slide_out_left"/>
  
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"/>
</RelativeLayout>


Navigate to app > res and Create a New Android Resource Directory and Add the following Animation Files to it. Refer to the How to add Slide animation between activities in android?

XML




<?xml version="1.0" encoding="utf-8"?>
    <!-- slide_in_right animation file -->
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="100%p"
        android:toXDelta="0" />
</set>


XML




<?xml version="1.0" encoding="utf-8"?>
      <!-- slide_out_left animation file -->
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0"
        android:toXDelta="-100%p" />
</set>


Step 3: Working with the MainActivity File

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

Java




import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    // Declaration of variables
    private TextSwitcher textSwitcher;
    private Button nextButton;
    private int stringIndex = 0;
  
    // Initialization of string array to store the text
    // which is to be displayed on layout
    private String[] row = {"Hi!", "Welcome", "to", "Geeks", "for", "Geeks"};
    private TextView textView;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        textSwitcher = findViewById(R.id.textSwitcher);
        nextButton = findViewById(R.id.button);
  
        // Setting a click listener on the NEXT button
        nextButton.setOnClickListener(v -> {
            // Adding condition to revisit the array
            if (stringIndex == row.length - 1) {
                stringIndex = 0;
                textSwitcher.setText(row[stringIndex]);
            } else {
                // otherwise display next string in array
                textSwitcher.setText(row[++stringIndex]);
            }
        });
  
        // Creating textView for the textSwitcher
        textSwitcher.setFactory(() -> {
            textView = new TextView(MainActivity.this);
  
            // Defining attributes for the text to be displayed
            textView.setTextSize(60);
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
  
            // #0F9D58 is GFG's applied theme colour
            textView.setTextColor(Color.parseColor("#0F9D58"));
            return textView;
        });
        textSwitcher.setText(row[stringIndex]);
    }
}


Kotlin




import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.widget.Button
import android.widget.TextSwitcher
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
  
class MainActivity : AppCompatActivity() {
  
    // Declaration of variables
    private lateinit var textSwitcher: TextSwitcher
    private lateinit var nextButton: Button
    private var stringIndex = 0
  
    // Initialization of string array to store the text
    // which is to be displayed on layout
    private val row = arrayOf("Hi!", "Welcome", "to", "Geeks", "for", "Geeks")
    private lateinit var textView: TextView
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        textSwitcher = findViewById(R.id.textSwitcher)
        nextButton = findViewById(R.id.button)
  
        // Setting a click listener on the NEXT button
        nextButton.setOnClickListener {
            // Adding condition to revisit the array
            if (stringIndex == row.size - 1) {
                stringIndex = 0
                textSwitcher.setText(row[stringIndex])
            } else {
                // otherwise display next string in array
                textSwitcher.setText(row[++stringIndex])
            }
        }
  
        // Creating textView for the textSwitcher
        textSwitcher.setFactory {
            textView = TextView(this)
  
            // Defining attributes for the text to be displayed
            textView.textSize = 60f
            textView.gravity = Gravity.CENTER_HORIZONTAL
  
            // #0F9D58 is GFG's applied theme colour
            textView.setTextColor(Color.parseColor("#0F9D58"))
            textView
        }
        textSwitcher.setText(row[stringIndex])
    }
}


Output:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments