Recipe Using Buttons and Text View

To fully demonstrate multiple activities, it is useful to use a trigger event. A button press is introduced here for that purpose. The steps to adding a button to a given layout and assigning an action to a button press are

1. Put a button in the designated layout XML file: <Button android:id="@+id/trigger"

android:layout_width="100dip" android:layout_height="100dip" android:text="Press this button" />

2. Declare a button that points to the button ID in the layout file: Button startButton = (Button) findViewById(R.id.trigger);

3. Specify a listener for when the button is clicked: //setup button listener startButton.setOnClickListener(new View.OnClickListener() { //insert onClick here

4. Override the onClick function for the listener to do the required action: public void onClick(View view) {

// do something here

To show the result of an action, it is useful to change the text on the screen. The steps for defining a text field and changing it programmatically are

1. Put a text field in the designated layout XML file with an ID. It can also be initialized to some value (here, it can be initialized to the string named "hello" in the strings.xml file):

<TextView android:id="@+id/hello_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello"

2. Declare a TextView that points to the TextView ID in the layout file: private TextView tv = (TextView) findViewById(R.id.hello_text);

3. If the text needs to be changed, use the setText function: tv.setText("new text string");

These two UI techniques are used in the subsequent recipes in this chapter.A more complete demonstration of UI techniques is covered in Chapter 4.

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook


Post a comment