Android TextSwitcher and ImageSwitcher Example Tutorial

Android TextSwitcher and ImageSwitcher are classes used to add animations to texts and images as they are being displayed on the screen to make them visually appealing. In this tutorial we’ll implement each of these.

Android TextSwitcher and ImageSwitcher Overview

The TextSwitcher and ImageSwitcher provide us a simple way to add animated transitions. These classes are used for a smooth transition animation in android view. Some usages of these are:

  • Navigating through a list of dates with Left and Right buttons
  • Changing numbers in a date picker
  • Countdown timer clock
  • Smooth transition for a news headlines slider

Android TextSwitcher

A TextSwitcher is a specialised form of ViewSwitcher that contains only children of type TextView. TextSwitcher is used to animate a TextView when the text changes. Two types of animations are required to switch between texts:

  • In Animation: with which Text come in the Screen
  • Out Animation: with which Text goes out from the Screen

Android ImageSwitcher

As you might have noticed in the previous tutorials containing ImageViews that the loading and rendering of images was abrupt and not smooth. Here ImageSwitcher comes to the rescue since it supports some form of transitions from one image to another. The implementation is given below.

The only thing left now is to add the Animation as given in the below snippet:

In short the following steps need to be implemented to use these classes:

  • Get the view reference using findViewById() method
  • Set a factory using switcher.setFactory()
  • Set an in-animation using switcher.setInAnimation()
  • Set an out-animation using switcher.setOutAnimation()
  • setFactory() is used to create new views
  • setText() on TextSwitcher works as follows:
    • It first removes the old text by using setOutAnimation()
    • It inserts the new text using setInAnimation()

Project Structure

android-switchers-project-229x450

Code

The layout for the MainActivity contains an ImageSwitcher, TextSwitcher and a Button in a RelativeLayout as shown below.

main.xml

The MainActivity consists of the Text an Image Switchers with their views created using setFactory(). The animations used are built in animations present in the android sdk. The application consists of three TextViews and ImageViews which are switched in cyclic order on each button click. The MainActivity.java is given below :

The onSwitch() method is invoked on button click. Below is our application in execution.
android-switchers-example

This brings an end to this tutorial. You can download the final Android Switchers Project from the link given below.

By admin

Leave a Reply

%d bloggers like this: