O'Reilly logo

Programming Android by Zigurd Mednieks, G. Blake Meike, Masumi Nakamura, Laird Dornin

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

Wiring Up the Controller

Assembling a Graphical Interface demonstrated a View with two buttons. Although the buttons look nice—they even become highlighted when clicked—they aren’t very useful. Clicking them doesn’t actually do anything.

The Controller described how the Android Framework translates external actions (screen taps, keypresses, etc.) into events that are enqueued and then passed into the application. Example 7-4 shows how to add an event handler to one of the buttons in the demo so that it does something when it is clicked.

Example 7-4. Wiring up a button

@Override public void onCreate(Bundle state) {
    super.onCreate(state);
    setContentView(R.layout.main);

    final EditText tb1 = (EditText) findViewById(R.id.text1);
    final EditText tb2 = (EditText) findViewById(R.id.text2);

    ((Button) findViewById(R.id.button2)).setOnClickListener(
        new Button.OnClickListener() {
            // mRand is a class data member
            @Override public void onClick(View arg0) {
                tb1.setText(String.valueOf(mRand.nextInt(200)));
                tb2.setText(String.valueOf(mRand.nextInt(200)));
            }
        }
    );
}

When run, this version of the application still looks a lot like Figure 7-2. Unlike the earlier example, though, in this version, every time a user clicks the button labeled “Green” the numbers in the EditText boxes change. This is illustrated in Figure 7-4.

Working button

Figure 7-4. Working button

While simply changing numbers isn’t very interesting, this small ...

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