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;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.your_textview);
...
}


and you are using mTextView.setText(something);

replace your onCreate's code with this:


Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);

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

@Override
public View makeView() {
TextView t = new TextView(YourActivity.this);
t.setGravity(Gravity.CENTER);
return t;
}
});

mTextSwitcher.setInAnimation(in);
mTextSwitcher.setOutAnimation(out);


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

1 comment: