Button Creation and Button Action in Android

posted Jan 25, 2011, 2:29 AM by Thiyagaraaj M   [ updated Aug 20, 2011, 4:33 AM ]

Create Button and Button Action in Android simple example code

XML Code:

<?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="Example Application"
    />
 <Button android:id="@+id/btn1"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Example Application"
    />
</LinearLayout>

Java Code

package com.example.android;

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 AndroidExample extends Activity {
    /** Called when the activity is first created. */
    
    Button Btn;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Btn = (Button) findViewById(R.id.btn1);
        
        Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {            
                Message("Im Button");
            }
        });
        
    }
    
    public void Message(String Msg)
    {
        Toast.makeText(AndroidExample.this, Msg.toString(), Toast.LENGTH_SHORT).show();
    }
}

Screen Shot



List Of Android Articles

Comments