So far, you have seen how to
handle the click events by implementing
onClick() method, which
is invoked when the button is clicked. Imagine that we want to provide a little counter telling
the user how many characters of input are still available out of the
maximum of 140. To do that, we need another type of listener.
Android provides many
different listeners for various events, such as touch, click, and so on.
In this case, we’re going to use
TextWatcher to watch
for text changes in the edit text field. Steps for this listener are
similar to the steps for
OnClickListener and many other
From the user’s
standpoint, we’ll add another
TextView to our layout to indicate how many
characters are still available. This text will change color, from green
to yellow to red, as the user approaches the 140-character limit.
In Java, we’ll implement
TextWatcher and attach it to the
field where the user is typing the actual text. The
TextWatcher methods will be invoked as the
user changes the text, and based on the amount of text entered, we’ll
update the counter. See Example 6-6.
Example 6-6. res/layout/status2.xml
<?xml version="1.0" encoding="utf-8"?> <!-- Main Layout of Status Activity --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <!-- Title TextView--> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" ...