O'Reilly logo

Android Application Development by G. Blake Meike, Zigurd Mednieks, John Lombardo, Rick Rogers

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 highlight when clicked—they aren’t very useful. Clicking them doesn’t actually do anything.

The discussion of The Controller described how the Android framework translates external actions (screen taps, key presses, etc.) into events that are enqueued and then passed into the application. Example 10-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 10-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() {
            @Override public void onClick(View arg0) {
                tb1.setText(String.valueOf(rand.nextInt(200)));
                tb2.setText(String.valueOf(rand.nextInt(200)));
            }
        }
    );
}

When run, this version of the application still looks a lot like Figure 10-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 10-4.

Working button

Figure 10-4. Working button

Simply changing numbers isn’t very interesting, but this small example demonstrates ...

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