Thursday 5 September 2013

Multiple Button Click Listener

Multiple Button Listener

Now we'll learn how to manage Multiple Button click Event Listener.
As you have learn the single button click event in previous tutorial.
Now we'll Move to the Multiple Buttons Tutorial.

1.activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:orientation="vertical">

    <Button

        android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="test1" />
    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="test2" />
    <Button
        android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="test3" />
    <Button
        android:id="@+id/btn4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="test4" />


</LinearLayout>


2.MainActivity.java

package com.sri.buttontest;

import android.app.Activity;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

Button btn1,btn2,btn3,btn4;

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
btn4 = (Button) findViewById(R.id.btn4);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
}

@Override

public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn1:
Toast.makeText(getApplicationContext(), "test1 is clicked", Toast.LENGTH_LONG).show();
break;
case R.id.btn2:
Toast.makeText(getApplicationContext(), "test2 is clicked", Toast.LENGTH_LONG).show();
break;
case R.id.btn3:
Toast.makeText(getApplicationContext(), "test3 is clicked", Toast.LENGTH_LONG).show();
break;
case R.id.btn4:
Toast.makeText(getApplicationContext(), "test4 is clicked", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}

}
3. That's all.Run the Project Now.
Comments and doubts are encouraged.
Thank you.

No comments:

Post a Comment