Home » Create Button Programmatically in Kotlin

Create Button Programmatically in Kotlin

create button programmatically kotlin

Today in this post I am going to show you, how to create a button programmatically in Kotlin.

First I created a new android studio project with an empty activity and removed the default hello world text view and replaced ConstrainLayout with LinearLayout in activity_main.xml.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

Also, I have set LinearLayout orientation to vertical and gave an id “linear_layout_container” to it.

I have added a few colors in res->values->colors.xml file, for our button background and text color.


<?xml version="1.0" encoding="utf-8"?>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorPrimaryDark">#3700B3</color>
    <color name="colorAccent">#03DAC5</color>
    <color name="mycolor">#E84A5F</color>
    <color name="white">#FFFFFF</color>

In MainActivity.kt file, we are going to writing our Kotlin code to create a button programmatically.

package com.example.buttoninkotlin
import android.os.Bundle
import android.widget.Button
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        val button = Button(this)
        button.text = "Simple Button"
        button.setBackgroundColor(ContextCompat.getColor(this, R.color.mycolor))
        button.setTextColor(ContextCompat.getColor(this, R.color.white))
        button.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
        button.setOnClickListener {
            Toast.makeText(this, "Button Clicked!!!", Toast.LENGTH_LONG).show()

In the above code, we have created a button named “Simple Button” and we have also set the button background color and text color. Button width is set to match parent and height to wrap content. And the button is added to the linear layout.

We have set an on-click listener to that button when it is clicked a toast message will be displayed.

That’s it, now if you run this code you will see a button with the label “Simple Button”. If you click this button a toast message “Button Clicked!!!” will be displayed on the screen.

create button programmatically kotlin output

It is good to practice to always create any view inside the UI thread. If you try to create a view outside the UI thread you will get an error or your app will crash.

Leave a Reply

Your email address will not be published.