Kotlin Android Create Button Programmatically

Creating a new Button programmatically at a point in the program requires it to be in UI thread. And also we need the application context to create any new View. Android prevents any View to be created outside the UI thread by throwing a build error.

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: Following is the activity_main.xml containing an empty LinearLayout to which we shall add the dynamic Button.

<?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.farizgaskin.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: 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.

package com.farizgaskin.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:

Conclusion

We hope you enjoyed this tutorial. See you next time!

Leave a Reply

Your email address will not be published. Required fields are marked *