In Android we can set click listener by three ways
- Setting individual click listener for each element.
- Implementing OnClickListener in activity level.
- Creating a separate function for handling button click and add this function in xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.bm.buttonclickeg.MainActivity"> <Button android:id="@+id/btn_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 1" /> <Button android:id="@+id/btn_two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 2" /> <Button android:id="@+id/btn_three" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myBtnClick" android:text="Button 3" /> </LinearLayout>
In the above example btn_three I have added a property android:onClick=”myBtnClick” myBtnClick is a function I have defined in activiy
MainActivity.java
package com.example.bm.buttonclickeg; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //option 1 Button btn1 = (Button) findViewById(R.id.btn_one); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "Created individual click listener", Toast.LENGTH_SHORT).show(); } }); //option 2 Button btn2 = (Button) findViewById(R.id.btn_two); btn2.setOnClickListener(this); } //option 2 @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_two: Toast.makeText(MainActivity.this, "Implemented click listener in activity", Toast.LENGTH_SHORT).show(); break; } } //option 3 // This function I have added in the btn_tree xml public void myBtnClick(View v) { Toast.makeText(MainActivity.this, "Created a separate function for handling button click and added this function in button xml", Toast.LENGTH_SHORT).show(); } }