button1

Android button Click Example

In previous tutorials we have learn about TextView now in this tutorial we are going to learn how button click and how button click event OnClickListener works.Just watch the below image.

 

button1

You can also use OnClickListener as anonymous inner class .

Example:-

btn_click.setOnClickListener(new OnClickListener() {
@Override

public void onClick(View v) {
tv_result.setText("You have click on Button");

}});

get project code below.


ButtonClickActivity.java


package com.androidfromhome.buttonclick;

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

public class ButtonClickActivity extends Activity implements OnClickListener {

private Button btn_click;
private TextView tv_result;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_click);
tv_result=(TextView)findViewById(R.id.tv_result);

btn_click=(Button)findViewById(R.id.btn_click);

btn_click.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_click:
tv_result.setText("You have click on Button");
break;

default:
break;
}

}
}


activity_button_click.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.androidfromhome.buttonclick.ButtonClickActivity" >

<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Click Me" />

</LinearLayout>


Download Full Code

Leave a Reply

Your email address will not be published. Required fields are marked *

Get Widget