Tuesday, 13 June 2017

Working with multiple buttons in Android

Working-with-multiple-buttons-in-Android

Download Source Code


In this post you can learn how to work with multiple buttons , before that read how to work with buttons.

It is similar to that of working with buttons the difference is that we are going to work with multiple buttons .

We are just going to use a SWITCH case where the button id's are used in case: .

Let us start the project.

Open New Project and make a user interface by dragging dropping the buttons where you want , I recommend you to read the below two post to get grip on the Buttons.

How to display names using Button in Android 

Adding two numbers in Android

 After designing the user interface it will look like 

working-with-multiple-buttons

Edit the names of the buttons as Button 1, Button 2, Button 3 respectively.

Right click on the button to Edit Text.
renaming-button-name-in-android


resolving-warning


Do the same for all the buttons

renaming-button-names

Read how to remove the warning symbol 


resolving-warning

After that we need to start java coding.

We need to register these three buttons and implement the interface and add unimplemented methods

button-code-in-android

After that inside the onclick method we need to write the switch condition.

working-with-multiple-buttons-in-android-java-code

This code is similar to that of switch case examples in c programs ,

the v.getId() will give you the id of the clicked button.

The other codes are similar to the previous posts.

The output will be:

working-with-multiple-buttons-in-android-output

working-with-multiple-buttons-in-android-output

working-with-multiple-buttons-in-android-output

working-with-multiple-buttons-in-android-output

How to use Android Phone as an Emulator


Working with multiple buttons in android will be useful in the upcoming examples so practice this example well and try your own ideas and practice that too.


Code of onClick() method:

public void onClick(View v)
    {
        switch (v.getId())
        {
        case R.id.button1:
           
            Toast.makeText(getApplicationContext(), "Button 1 is clicked", Toast.LENGTH_LONG).show();
           
            break;
           
        case R.id.button2:
           
            Toast.makeText(getApplicationContext(), "Button 2 is clicked", Toast.LENGTH_LONG).show();
           
            break;
           
         case R.id.button3:
   
            Toast.makeText(getApplicationContext(), "Button 3 is clicked", Toast.LENGTH_LONG).show();
   
            break;

        default:
            break;
        }
    }