: Beginning Android

The Rest of the Story

The Rest of the Story

In the original Now demo, the buttons face would show the current time, which would reflect when the button was last pushed (or when the activity was first shown, if the button had not yet been pushed).

Most of that logic still works, even in this revised demo (NowRedux). However, rather than instantiating the Button in our activitys onCreate() callback, we can reference the one from the XML layout:

package com.commonsware.android.layouts;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;
publicclass NowReduxextends Activity
implements View.OnClickListener {
Button btn;
public voidonCreate(Bundle icicle) {
public voidonClick(View view) {
private voidupdateTime() {

The first difference is that rather than setting the content view to be a view we created in Java code, we set it to reference the XML layout (setContentView(R.layout.main)). The R.java source file will be updated when we rebuild this project to include a reference to our layout file (stored as main.xml in our projects res/layout directory).

The other difference is that we need to get our hands on our Button instance, for which we use the findViewById() call. Since we identified our button as @+id/button, we can reference the buttons identifier as R.id.button. Now, with the Button instance in hand, we can set the callback and set the label as needed.

As you can see in Figure 5-1, the results look the same as with the original Now demo.

Figure 5-1.The NowRedux sample activity

: 1.482. /Cache: 3 / 0