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=""
        android:orientation="vertical" >
            android:text="Click Me" />
  2. Now attach an event Click Listener to the button. example:
    button = (Button) findViewById(;
    button.setOnClickListener(new OnClickListener() {/* Some Code */ });
  3. Here is the complete code for it
[code lang="java"] package com.demo.buttonexample; import; import android.content.Intent; import; 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(; button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("")); startActivity(browserIntent); } }); } }