Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a button dynamically in Android using Kotlin

Tags:

android

kotlin

How to add a button dynamically in Android using Kotlin?

I am new to Kotlin, please help.

like image 708
Pradeep Bishnoi Avatar asked Feb 05 '23 09:02

Pradeep Bishnoi


2 Answers

You can create a button dynamically by calling the constructor of the button.

var myButton = Button(this);

'this' will be the activity.

like image 103
Avijit Karmakar Avatar answered Feb 06 '23 23:02

Avijit Karmakar


Please try this:-

/* Create a new Button programmatically in Kotlin Android */

private fun createButtonDynamically() {
    // creating the button
    val dynamicButton = Button(this)
    // setting layout_width and layout_height using layout parameters
    dynamicButton.layoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
    )
    dynamicButton.text = "Dynamic Button"
    dynamicButton.setBackgroundColor(Color.GREEN)
    // add Button to LinearLayout
    mainLayout.addView(dynamicButton)


}
like image 41
Supriya Yadubansi Avatar answered Feb 06 '23 23:02

Supriya Yadubansi