13 June 2014

Buttons in Android (Part -1)

What we will do?
->We will make a button and perform action of opening toast when button is clicked

What we will need?
  • Adding button to activity_main.xml
  • Changes in MainActivity.java
Step 1 : Create a new Application. Go to File->New->Android Application Project

Step 2 : Give a name to your application as Samplebutton and package name as com.mia.samplebutton. Click Next continuously
Click Finish

Step 3 : Remove TextView "Hello World". Drag Button in activity_main.xml layout
activity_main.xml
<RelativeLayout 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"
    tools:context="com.mia.samplebutton.MainActivity" >

    <Button
      android:id="@+id/button1"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Click me" />

</RelativeLayout>

Step 4 : Open MainActivity.java from src->com.mia.samplebutton in Project Explorer.

MainActivity.java
package com.mia.samplebutton;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

                Button btn1 = (Button)findViewById(R.id.button1);
            
             btn1.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View v) {
            //Perform action when button clicked
            }});
}
}
You can open another page by clicking button by following this tutorial

Step 5 : Run the application. 
Stay Tuned with Made In Android

Previous Page Next Page Home
Top