Android Button Example [OnClick|Color|Design] in Kotlin

Android Button widget is the most important UI element in the Android app. You can perform Operations by button click like send Email, Message, WhatsApp, etc all this want action where Button is doing same. Button widget comes with default design and color schema but you can change its color, design, size, etc according to your requirements. Its also have some attribute which already implemented on Android SDK API, so you have to just configure it, nothing else. In this Android button Example, we will learn basic of Button widget.

Android Button Example [ OnClick | Color | Design ] in Kotlin tuorial

A button can have text or an icon or both text and an icon. When a user touches or a click on the button, that time action makes that communicate with other component or do something.

Text Button 

Android Text Button

Simple button with text only. Code for text button is below –

Text + Image Button 

Text and an icon – use the Button with the android:drawableLeft attribute, don’t forget add images “baseline_star_black.png” mipmap image resource.

Button ON Clicks 

If user click on a Button then Button object receive on-click event.

To perform a event , add the android:onClick attribute to the <Button> element in your XML layout.

The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

For example – layout with a button using android:onClick:

 The Activity which hosts that layout have following method to handles the click event (code in Kotlin)

Button – OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout.

To declare the event handler programmatically by calling setOnClickListener(View.OnClickListener). For example: you need button id and set Listener.

Button Color attribute – android:background

Androd color button

You can change button color by using android:background attribute.

Let’s Build a Complete Example of Android Button :

Step 1. Create new project “Build Your First Android App in Kotlin
Step 2. Add the following code in “activity_main.xml” resource file

Don’t forget add image file “baseline_star_black.png

Step 3. Open“MainActivity.kt” and add following code 
Step 4. Now Run the application, in emulator or On you android device
Output screenshot Android Button example :
Android Button Example [ OnClick | Color | Design ] in Kotlin tuorial output

Download source code Android Button in kotlin

Note: This example (Project) is developed in Android Studio 3.1.3. Tested on Android 9 ( Android-P), compile SDK version API 26: Android 8.0 (Oreo)



Coding in Kotlin

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.