Describe how to implement a click listener in Android.

Instruction: Explain the process of setting up a click listener for a button in an Android application, including any necessary code snippets.

Context: This question assesses the candidate's practical skills in handling user interactions within Android applications. It tests their ability to write code that responds to user actions, a fundamental aspect of creating interactive and responsive apps.

Updated

Official answer

For a View-based screen, create a Button or obtain it from an installed layout, then register a View.OnClickListener. The callback handles the action; do not perform blocking network or database work directly in it.

This complete Activity class creates its button programmatically, so it does not require a layout resource. Add it as an internal activity in an existing Android application manifest using its fully qualified class name and android:exported="false", then launch it from that app. It is a small click example, not a complete app project.

package com.example.clickdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public final class ClickActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Button button = new Button(this);
        button.setText("Show message");
        setContentView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(
                    ClickActivity.this,
                    "Button clicked",
                    Toast.LENGTH_SHORT
                ).show();
            }
        });
    }
}

For an XML layout, call setContentView with that layout first and obtain the matching button through View Binding or findViewById. In a Fragment, use its created view in onViewCreated and release retained binding references in onDestroyView; an Activity's lookup is not a generic Fragment lookup.

Test touch and keyboard/assistive activation, repeated clicks and returning to the screen. A real asynchronous submission should expose progress/error state and prevent unintended duplicate operations. Move these demonstration strings into localized resources in the application.

Button click events, Activity API, Fragment view lifecycle

Related Questions