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 programmatically. Here are the some usage of TextSwitcher:
- Changing numbers in a Date Picker
- Countdown of timer clock
- In Animation
- Out Animation
TextSwitcher uses two type of animations:
Approach:
- Add the following code in the activity_main.xml file.activity_main.xml
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
RelativeLayout
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
=
"@android:anim/slide_in_left"
android:outAnimation
=
"@android:anim/slide_out_right"
/>
<
Button
android: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
package
com.madhav.maheshwari.gfgTextSwitcher;
import
android.graphics.Color;
import
android.os.Bundle;
import
android.view.Gravity;
import
android.view.View;
import
android.widget.Button;
import
android.widget.TextSwitcher;
import
android.widget.TextView;
import
android.widget.ViewSwitcher;
import
androidx.appcompat.app.AppCompatActivity;
public
class
MainActivity
extends
AppCompatActivity {
private
TextSwitcher textSwitcher;
private
Button nextButton;
private
int
index =
0
;
private
String[] arr
= {
"GeeksForGeeks"
,
"A"
,
"Computer"
,
"Science"
,
"Portal"
,
"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);
nextButton.setOnClickListener(
new
View.OnClickListener() {
@Override
public
void
onClick(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 TextSwitcher
textSwitcher.setFactory(
new
ViewSwitcher.ViewFactory() {
@Override
public
View makeView()
{
textView
=
new
TextView(
MainActivity.
this
);
textView.setTextColor(
Color.parseColor(
"#219806"
));
textView.setTextSize(
40
);
textView.setGravity(
Gravity.CENTER_HORIZONTAL);
return
textView;
}
});
// This is used to set the text
// when app starts which is
// at index i.e 0.
textSwitcher.setText(arr[index]);
}
}
Output: