Multiple Android Button Tutorial


Multiple Android Button Tutorial

Hi guys! Today we’re gonna do an example application of android Push Buttons.

Push-buttons can be pressed, touched, or clicked by the user to invoke an event or action in your application.

This example will show you how to make two android buttons working (you can add more if you want).

It also uses an Android toast so if you’re not yet familiar with it, you may visit also view my post about Android Toasts here.

So, after creating a new project, we will modify two files.

The main activity file, which is in this case, the AndroidButtons.java and the layout file which is the main.xml

AndroidButtons.java

package com.example.AndroidButtons;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class AndroidButtons extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    try {
    View.OnClickListener handler = new View.OnClickListener(){
        public void onClick(View v) {
            //we will use switch statement and just
            //get thebutton's id to make things easier
            switch (v.getId()) {

                case R.id.ShowToastBtn: //toast will be shown
                    Toast.makeText(getBaseContext(), "You Clicked Show Toast Button!", Toast.LENGTH_SHORT).show(); 
                    break;
                case R.id.FinishBtn: //program will end
                    finish();
                    break;
            }
        }
    };
        
    //we will set the listeners
    findViewById(R.id.ShowToastBtn).setOnClickListener(handler);
    findViewById(R.id.FinishBtn).setOnClickListener(handler);
        
    }catch(Exception e){
         Log.e("Android Button Tutorial", e.toString());
    }  
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
    android:layout_width="98px"
    android:layout_height="wrap_content"
    android:text="Show Toast" 
    android:id="@+id/ShowToastBtn">
    </Button>
    
    <Button
    android:layout_width="98px"
    android:layout_height="wrap_content"
    android:text="Finish" 
    android:id="@+id/FinishBtn">
    </Button>
</LinearLayout>

When you run this script it will look like this:

SC20110720-085607

When you click the “Show Toast” Button, it will look like this:

SC20110720-085600

When you click “Finish”, obviously, the program will end. Haha!

,

7 responses to “Multiple Android Button Tutorial”

Leave a Reply

Your email address will not be published. Required fields are marked *