O'Reilly logo

Learning Android by Marko Gargenta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Other UI Events

So far, you have seen how to handle the click events by implementing OnClickListener and providing the 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 listeners.

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" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required