Sometimes, To make the app pages look more attractive we need to apply different animations to our mobile content and for this Android provides developers two classes namely TextSwitcher and ImageSwitcher in order to have a transition animation in an Android View. TextSwitcher is specially designed to contain only TextView as a child. It is used to animate any text on the app page. Whenever the setText(CharSequence) method is called, TextSwitcher animates the current text out and animates the new text in. TextView and TextSwitcher work in a similar way. Similarly, an ImageSwitcher replaces an ImageView. It also contains only ImageView as a child and animates the views in and out.
Let us see the steps to implemen TextSwitcher.
First we will define our XML file which will contain a TextSwitcher. Below is a sample.xml.
1 2 3 4 |
<TextSwitcher android:id="@+id/switcher" android:layout_width="match_parent" android:layout_height="wrap_content"/> |
Now in our Activity class we will initialise this TextSwitcher.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//Get the TextSwitcher mSwitcher = (TextSwitcher) findViewById(R.id.switcher); //Set the factory to supply TextView mSwitcher.setFactory(mFactory); //Set Animations Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); mSwitcher.setInAnimation(in); mSwitcher.setOutAnimation(out); // Set the initial text without an animation mSwitcher.setCurrentText(String.valueOf(mCounter)); |
As you can see in the above code segment first we have picked the view and the set a ViewFactory on the TextSwitcher. ViewFactory actually provide the view which will be loaded when the view is changed.Below is the example code for ViewFactory.
1 2 3 4 5 6 7 8 9 10 |
private ViewFactory mFactory = new ViewFactory() { @Override public View makeView() { TextView t = new TextView(MainActivity.this); t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); t.setTextAppearance(MainActivity.this, android.R.style.TextAppearance_Large); return t; } }; |
Now we are all set. Now whenever we call the setText function of the TextSwitcher it will change the text according to the animation applied.
That’s all !!! Just by following these simple steps you can also implement ImageSwitcher.
Thank you very much. This is Vedesh Kumar signing off.