Android Button setOnClickListener Example


Nov 04, 2013    Janaki Mahapatra, Android

  1. Add a button to your "res/layout/main.xml" file. exmaple:
    <?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/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click Me" />
    
    </LinearLayout>
  2. Now attach an event Click Listener to the button. example:
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {/* Some Code */ });
  3. Here is the complete code for it
[code lang="java"] package com.demo.buttonexample; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.Button; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends Activity { Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnClick(); } public void btnClick() { button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.howtosolvenow.com")); startActivity(browserIntent); } }); } }