Friday, December 11, 2009

Making TextSwitcher text bigger

I found that the TextSwitcher doesn't honor the textSize property the way I had hoped. I could put that property as high or low as I wanted in the layout XML page and it didn't change anything. However, I found I was barking up the wrong tree. Apparently the TextSwitcher is just a wrapper for TextView objects. What I needed to do is dig down a little deeper and change the size on the TextView object inside of the TextSwitcher rather than the TextSwitcher itself.

A TextSwitcher has a ViewFactory, which controls what happens when the text is changed. ViewFactory has one public method that needs to be overridden - makeView. This is called internally whenever setText is called on the ViewFactory. My original setText simply created a top-left anchored TextView and returned it. This is the code I had used -

public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.LEFT);
return t;
}

I figured out that this is where I could sneak in and increase the size of my TextSwitcher's text. I simply added a line in that method that called the setTextSize method on my new TextView object -

public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.LEFT);
t.setTextSize(TypedValue.COMPLEX_UNIT_DIP, getResources().getDimension(R.dimen.guide_text_size));
return t;
}

As you can see, I had it pull in a size that I had defined elsewhere in an XML file. I used a constant defined in TypedValue to specify that I wanted my text size to be in dp. And that's it!