Sunday, November 14, 2010

Android Tip: TextSwitcher and ImageSwitcher

Quick android tip.

If you are using TextView or ImageView in your view and you are changing it's content when the user interacts, you can try using TextSwitcher and ImageSwitcher.

They work in a very similar way. The steps to use them are the following:

* Get the view using findViewById() or construct in your code like any normal android view.
* Set a factory using switcher.setFactory().
* Set an in animation using switcher.setInAnimation().
* Set an in animation using switcher.setOutAnimation().

So, if your code looks something like this:

private TextView mTextView;

public void onCreate(Bundle savedInstanceState) {
mTextView = (TextView) findViewById(;

and you are using mTextView.setText(something);

replace your onCreate's code with this:

Animation in = AnimationUtils.loadAnimation(this,
Animation out = AnimationUtils.loadAnimation(this,

mTextSwitcher = (TextSwitcher) findViewById(;
mTextSwitcher.setFactory(new ViewFactory() {

public View makeView() {
TextView t = new TextView(YourActivity.this);
return t;


That's it. You get some cool animations for free.

1 comment: