Monday, October 31, 2011

TextWatchers and onRestoreInstanceState()

There's a small timing issue I'd like to mention because it's bitten me a few times now.

When you want to observe changes to an EditText, you add a TextWatcher to it (via TextView. addTextChangedListener()). There are a lot of uses for TextWatchers, like implementing your own autocomplete or filters based on a dynamic EditText. The only thing you have to be careful of is whether the text was changed by the user or the code - the listener fires either way.

What's worth knowing about an EditText is that it will save and restore the state of the text inside of it within your Activity. That means that when you rotate the screen, the EditText will restore the text that was inside of it. And most importantly, the automated restoring of the text on rotation causes the TextWatcher's methods to fire. Like I said - the TextWatcher doesn't discern between whether the user changed the EditText or the system did.

The solution is simple - just don't add the TextWatcher until after the EditText's content has been restored. It restores itself in Activity.onRestoreInstanceState(), which makes Activity.onResume() the preferred time to add TextWatchers to any EditTexts.

Monday, October 10, 2011

Android Drawable XML Talk

I recently gave a talk on the basics of Android drawable resources (via XML).

There's a recording I made of the talk - not super, but functional. I had to split it into two parts because of time restrictions on YouTube. Here's part one and part two.

I also have a few links that may be useful (whether you watch the talk or not):

- The slides for the presentation

- Official Android drawable resource documentation

- My drawable XML documentation

- The github project with my samples