How to add a button dynamically in Android using Kotlin?
I am new to Kotlin, please help.
You can create a button dynamically by calling the constructor of the button.
var myButton = Button(this);
'this' will be the activity.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With