Friday, August 24, 2012

Android Simple Button Click Example


SIMPLE BUTTON CLICK

SOURCE CODE [main.xml] is

<?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">
               
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

                <Button android:id="@+id/button1"
android:layout_width="100px"
                                android:layout_height="wrap_content"
android:text="Button 1" />

                <Button android:id="@+id/button2"
android:layout_width="100px"
                                android:layout_height="wrap_content"
android:text="Button 2" />

</LinearLayout>

SOURCE CODE [ButtonExample.java] is

package com.ButtonExample;

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 ButtonExample extends Activity
{
Button b1,b2;

public void onCreate(Bundle savedInstanceState)
{
                                super.onCreate(savedInstanceState);
                                setContentView(R.layout.main);

b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);

b1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),
                                                                                "You have clicked Button 1", Toast.LENGTH_LONG);
                                                                msg.show();
}
                                });

b2.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),
                                                                                "You have clicked Button 2", Toast.LENGTH_LONG);
 msg.show();
}
                                });
 }
}

The OUTPUT will be


https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrlH5rrcWFVBfOp7w76gbMZkVUSFhOt3flB2rxYbvEo1s1venSjC4EXgZzrKCK0i0z9IUvzRG66LghKyN7EIXVdJ_ROx2OnoC2nANM6B3qGyQIidOCgtZ-Iq8XW_F-unTCBraSqf-D0Io/


https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwuXfDHn2vDt0DZ3s6en0qFrB_4fTTMbcJmnzTVpDdd7tN30mg66WzyVrAKc3tBPa7Opr-hclj6NjHU7vVd0LjKECLXw-M4pELh1c58WniK48WTO4_zlwNRvKR_rZSHGIFA9JAr8VAt_M/