Книга: Beginning Android

The Rest of the Story

The Rest of the Story

In the original Now demo, the button’s 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 activity’s 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;
public class NowRedux extends Activity
 implements View.OnClickListener {
 Button btn;
 @Override
 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.main);
  btn=(Button)findViewById(R.id.button);
  btn.setOnClickListener(this);
  updateTime();
 }
 public void onClick(View view) {
  updateTime();
 }
 private void updateTime() {
  btn.setText(new Date().toString());
 }
}

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 project’s 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 button’s 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.144. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз