Android Button setOnClickListener Method Guide | Generated by AI

Home 2026.01

Question: To set an onClick listener for a Button in code, which method is commonly used?

A) button.setOnClickListener()
B) button.addClickListener()
C) button.onClick()
D) button.setClickEvent()

Answer:

The correct answer is A) button.setOnClickListener().

In Android development (using Java or Kotlin), the standard and most commonly used method to programmatically set an onClick listener for a Button (or any View) is setOnClickListener(). This method takes an implementation of the View.OnClickListener interface, typically provided via an anonymous inner class, lambda (in Kotlin), or a separate listener object.

Example in Java:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Handle click event
    }
});

Example in Kotlin:

button.setOnClickListener {
    // Handle click event
}

Why not the others?

Note: The user’s selection of “C” is incorrect. The correct choice is A.

References:


Back

x-ai/grok-4.1-fast

Donate