In Android we can set click listener by three ways
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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(); } } |