Button in android

Lets see how to insert a button in your android application UI.

Have a look at the Xml layout now:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >
 <Button
 android:id="@+id/btn"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Click This Button"
 />
</LinearLayout>

Now what do we first do in the code? Of Course, set the Content view as the above XML layout.

 setContentView(R.layout.main);

Then, create the reference to class Button and find the view by the id which is ‘btn'(just look at the above XML code.Look at the line android:id=”@+id/btn”)

 Button button;
 button =(Button)findViewById(R.id.btn);

Lastly we need to implement the onClickListener as shown below:

button.setOnClickListener(new OnClickListener() {
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 Toast.makeText(getApplicationContext(), "You clicked the button", Toast.LENGTH_LONG).show();
 }
 });

Here, when the button is clicked a Toast is displayed.

Now the complete code is given below :

package com.deepthi.mybutton;
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 MyButtonDemoActivity extends Activity {
 /** Called when the activity is first created. */
 Button button;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 button =(Button)findViewById(R.id.btn);
 button.setOnClickListener(new OnClickListener() {

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 Toast.makeText(getApplicationContext(), "You clicked the button", Toast.LENGTH_LONG).show();
 }
 });
 }
}
The Screen Shot of the Out put is shown below:

When the button is clicked the screen looks as given below:

Advertisements

, , ,

  1. #1 by VISHNU MOHAN on February 17, 2012 - 10:02 pm

    gud one sis……….. 🙂

    • #2 by Deepthi G on February 19, 2012 - 12:43 pm

      Hey bro
      Thanks a lot… 🙂 keep reading!!

  2. #3 by Anthony Gholar on March 10, 2012 - 2:03 pm

    Would love to perpetually get updated great website!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: