How to add TextSwitcher with animation in Android using Java
A TextSwitcher is used to animate a text on a screen. It is the child class of the ViewSwitcher class. It contains only one child of type TextView. In order to set animation on TextSwitcher we have to add animation tag or we can add programtically. Here are the some usage of TextSwitcher:
- Changing numbers in a Date Picker
- Countdown of timer clock
TextSwitcher uses two type of animations:
- In Animation
- Out Animation
Approach:
- Add the following code in the activity_main.xml file.
activity_main.xml
<?xmlversion="1.0"encoding="utf-8"?><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextSwitcherandroid:id="@+id/textSwitcher"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="80dp"android:inAnimation="@android:anim/slide_in_left"android:outAnimation="@android:anim/slide_out_right"/><Buttonandroid:id="@+id/button"android:textSize="20sp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="Next"/></RelativeLayout> - Now add the following code in the MainActivity.java file.
MainActivity.java
packagecom.madhav.maheshwari.gfgTextSwitcher;importandroid.graphics.Color;importandroid.os.Bundle;importandroid.view.Gravity;importandroid.view.View;importandroid.widget.Button;importandroid.widget.TextSwitcher;importandroid.widget.TextView;importandroid.widget.ViewSwitcher;importandroidx.appcompat.app.AppCompatActivity;publicclassMainActivityextendsAppCompatActivity {privateTextSwitcher textSwitcher;privateButton nextButton;privateintindex =0;privateString[] arr= {"GeeksForGeeks","A","Computer","Science","Portal","For","Geeks"};privateTextView textView;@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textSwitcher = findViewById(R.id.textSwitcher);nextButton = findViewById(R.id.button);nextButton.setOnClickListener(newView.OnClickListener() {@OverridepublicvoidonClick(View v){// when the text switcher// reaches at the end// of our array. It will// be reset to 0.if(index == arr.length -1) {index =0;textSwitcher.setText(arr[index]);}else{textSwitcher.setText(arr[++index]);}}});// Here we have to create// a TextView for our TextSwitchertextSwitcher.setFactory(newViewSwitcher.ViewFactory() {@OverridepublicView makeView(){textView=newTextView(MainActivity.this);textView.setTextColor(Color.parseColor("#219806"));textView.setTextSize(40);textView.setGravity(Gravity.CENTER_HORIZONTAL);returntextView;}});// This is used to set the text// when app starts which is// at index i.e 0.textSwitcher.setText(arr[index]);}}
Output:
- Countdown of timer clock



