Recipe 2.1 Using Buttons

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
Buttons.zip

The Button view is one of the most commonly used views on an activity. This recipe shows you the basic types of Button views and the various ways to handle their events.

Solution

Assume you have the following code snippet in the activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:onClick="onClick" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 2" 
        android:onClick="onClick" />
    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 3" />
    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 4" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 5" />

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton"
        android:onClick="onToggle" />

</LinearLayout>

The most common way to handle ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.