Monday 19 November 2012

Android Button & TextView Tutorial



In this tutorial, I'm going to show you how to display a simple button, add a click listener.When  user click on the button the text in the TEXTVIEW will change.

1.Create an android project.

  Project Name   : ButtonDemo
 Package        : com.roney.buttontxt
 Main Activity  : ButtonDemoActivity.java
 Build Target   : Android 2.2

  Refer:- Drag & Drop Elements in FORM WIDGET

2.Adding a Button and a TextView

  Open " res/layout/main.xml " file and add a Button &  a TextView

<?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/bt"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Click Me" />

     <TextView

      android:id="@+id/tv"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Click on the Button to change this text" />
   
    </LinearLayout>


3.Adding click listener to the button

Open ButtonDemoActivity.java class file.

Attach a click listenerto the button.When a user click on the button,the text of TextView will change

ButtonDemoActivity.java

package com.demo.buttontxt;

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

public class ButtonDemoActivity extends Activity 
{
 /** Called when the activity is first created. */
  
 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
      
  //Creating Button variable
  Button button = (Button) findViewById(R.id.bt);     
      
  //Adding Listener to button
  button.setOnClickListener(new View.OnClickListener() 
  {
         
  @Override
  public void onClick(View v) 
  {
  // TODO Auto-generated method stub
             
  //Creating TextView Variable
  TextView text = (TextView) findViewById(R.id.tv);
              
  //Sets the new text to TextView (runtime click   event)
  text.setText("You Have click the button");
  }
  });
  
  }
}


4.Running the application

  a)Result shows a Button & TextView






  b) When click on the button,text of TextView will change as






" If you like my tutorials let me know by your comments " 

2 comments:

Anonymous said...

Good one

Your simple content makes this tutorial unique.

Anonymous said...

Your tutorials are easy to follow

Bookmarked

:)