Android onClick Listener: A Short How-To Guide

Good ole’ Java, gotta love all the boilerplate! Am I right? Okay, so as we all know there’s a lot of boilerplate and verbosity involved in writing Java/Android code, so I just wanted to create this quick blog post demonstrating how to setup an OnClickListener to listen for and respond to button clicks in Android. Unfortunately the Android documentation doesn’t include a lot of code snippets so sometimes references like this are necessary. So without further ado, here is an XML layout file and an Android Activity written in Java demonstrating how to listen for onClick events in Android:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/my_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CLICK ME" />
</LinearLayout>
package blog.topherpedersen.uselesscameraapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton = findViewById(R.id.my_button);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Button Clicked!", Toast.LENGTH_LONG).show();
}
});
}
}
 

topherPedersen