Create a Button Programmatically in Kotlin Android

In Android, a Button can be added in an XML layout file, or it can be created in Kotlin code and attached to an existing layout at runtime. Creating a Button programmatically is useful when the number of buttons depends on user input, API data, app state, or a loop.

In this tutorial, we will create a Button widget programmatically in Kotlin Android and add it to a LinearLayout that already exists in the layout XML file.

Kotlin snippet to create a Button dynamically

The following Kotlin code creates a new Button, sets its layout parameters, and assigns the text shown on the Button.

</>
Copy
val button_dynamic = Button(this)
button_dynamic.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
button_dynamic.text = "Dynamic Button"

A View should be created and updated on the Android main UI thread. In a normal Activity onCreate() method, you are already on the UI thread, so you can create the Button and add it to the layout directly.

In this Android Tutorial, we shall learn how to create a Button programmatically and add the Button to a LinearLayout using Kotlin.

activity_main.xml with an empty LinearLayout for the dynamic Button

activity_main.xml: Following is the activity_main.xml containing an empty LinearLayout to which we shall add the dynamic Button.

</>
Copy
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tutorialkart.myapplication.MainActivity">
    <LinearLayout
        android:id="@+id/ll_main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
    </LinearLayout>
 
</android.support.constraint.ConstraintLayout>

MainActivity.kt to add the Button to LinearLayout

MainActivity.kt: We shall create a new Button with text “Dynamic Button” and add it to the LinearLayout. This addition makes the dynamically created Button to be appended at the end of all child views present in the LinearLayout.

</>
Copy
package com.tutorialkart.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val ll_main = findViewById(R.id.ll_main_layout) as LinearLayout

        // creating the button
        val button_dynamic = Button(this)
        // setting layout_width and layout_height using layout parameters
        button_dynamic.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        button_dynamic.text = "Dynamic Button"
        // add Button to LinearLayout
        ll_main.addView(button_dynamic)
    }
}

Following is the Output with layout bounds :

Create a new Button programmatically in Kotlin Android - Kotlin Android Tutorial - www.tutorialkart.com
Create a new Button programmatically in Kotlin Android

Set Button text, size, margins, and position in Kotlin

The Button is created with Button(this). The this value is the Activity context. After creating the Button, you can set its text, layout width, layout height, margins, padding, and other properties before adding it to the parent layout.

</>
Copy
val button = Button(this)

val params = LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
)
params.setMargins(16, 16, 16, 16)

button.layoutParams = params
button.text = "Submit"
button.textSize = 18f
button.setPadding(24, 12, 24, 12)

ll_main.addView(button)

Use WRAP_CONTENT when the Button should take only the space required by its text. Use MATCH_PARENT when the Button should fill the available width or height of its parent.

Add a click listener to a programmatically created Android Button

A dynamic Button works like an XML Button after it is added to the layout. You can attach a click listener using setOnClickListener. The setOnClickListener method is not deprecated and is still the common way to handle Button clicks in Android views.

</>
Copy
button_dynamic.setOnClickListener {
    button_dynamic.text = "Clicked"
}

If you are using a modern Android project, avoid relying on deprecated Kotlin synthetic view accessors. Use findViewById or View Binding to get the parent layout, and then add the Button to it.

Create three Buttons dynamically in Kotlin Android

When you need more than one Button, create them inside a loop and add each Button to the same parent layout. This approach is useful for menus, filter chips, quiz options, or any screen where the number of actions is decided at runtime.

</>
Copy
val buttonLabels = listOf("One", "Two", "Three")

for (label in buttonLabels) {
    val button = Button(this)
    button.layoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
    )
    button.text = label

    button.setOnClickListener {
        button.text = "$label clicked"
    }

    ll_main.addView(button)
}

Where to place the Kotlin code for a dynamic Button

Place the Button creation code after setContentView(). The layout must be inflated before you call findViewById() and before you add child views to the parent layout.

</>
Copy
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val parentLayout = findViewById<LinearLayout>(R.id.ll_main_layout)

    val button = Button(this)
    button.text = "Dynamic Button"

    parentLayout.addView(button)
}

If you try to access the parent layout before setContentView(), Android will not find the layout from your screen, and the code may fail at runtime.

Common mistakes while adding a Button programmatically in Kotlin

  • Using the wrong parent layout parameters: Use LinearLayout.LayoutParams when the parent is a LinearLayout. For a ConstraintLayout, use ConstraintLayout.LayoutParams.
  • Adding the Button before the layout is ready: Call setContentView() first, then get the parent layout, and then add the Button.
  • Using a background thread for UI changes: Create and modify Android views on the main UI thread.
  • Forgetting to add the Button to a parent: Creating Button(this) alone does not display it. You must call addView() on a parent layout.
  • Expecting XML attributes to apply automatically: A programmatically created Button will use the properties you set in Kotlin and the default style from the app theme.

FAQs on creating a Button programmatically in Kotlin Android

How to create a Button in Kotlin Android?

Create a Button using Button(this), set its layout parameters and text, and add it to a parent layout using addView().

How do I add a Button to an Android layout programmatically?

First get the parent layout using findViewById. Then create the Button, configure it, and call parentLayout.addView(button).

Is Android onClick deprecated for Buttons?

setOnClickListener is not deprecated. You can use it safely for Buttons created in Kotlin code. Some older approaches, such as Kotlin synthetic view accessors, are deprecated, but the click listener itself is not.

How to create three Buttons dynamically in Android?

Create a list of button labels, loop through the list, create a Button for each label, and add each Button to the parent layout using addView().

Can I create a dynamic Button inside ConstraintLayout?

Yes. Use ConstraintLayout.LayoutParams instead of LinearLayout.LayoutParams, and set the required constraints before adding the Button to the ConstraintLayout.

Editorial QA checklist for this Kotlin Android Button tutorial

  • The tutorial shows how to create a Button using Kotlin code, not only XML.
  • The Button is added to an existing LinearLayout using addView().
  • The code places Button creation after setContentView().
  • The explanation identifies why correct layout parameters matter for the parent layout.
  • The FAQ answers common questions about dynamic Buttons, click listeners, and multiple Buttons.

Conclusion

In this Kotlin Android Tutorial, we have learned to create Button programmatically and add it to layout.