Working with Android Buttons

Buttons Attributes:

Inherited from android.widget.TextView Class –

  1. android:autoText

Inherited from android.view.View Class –

  1. android:background

We can create a button in the layout file in three ways using text, an icon, or both text and an icon:

  • With text, using the Button class:
  • With an icon, using the ImageButton class:
  • With text and an icon, using the Button class with the android:drawableLeft attribute:

Define Click Events in Button:

1.Using onClick:

When the user clicks a button, the Button object receives an on-click event.

  • Be public
  • Return as void
  • Define a View as its only parameter (this will be the View that was clicked)

2.Using OnClickListener:

Also, we can declare the click event handler programmatically in the activity java file. This might be needed if you instantiate the Button at runtime or you need to declare the click behavior in a Fragment subclass.

Button button = (Button) findViewById(;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something

Android Button Example with Listener:

Here we simply add two numbers. We are going to create two text fields and one button to sum of two numbers. If the user clicks the button, the sum of two input values is displayed as the Toast message. Here we see both the declaring ways of a button and output will be like this:

Using the onClick method:




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Golap Gunjan Barman

Golap Gunjan Barman

Hi everyone, myself Golap an Android app developer with UI/UX designer.