4

How to add a button dynamically in Android using Kotlin?

I am new to Kotlin, please help.

3
  • What u have tried ? Commented May 24, 2017 at 4:22
  • @8hubham : kotlin is new language for android. you can search on google Commented May 24, 2017 at 4:25
  • Question was very basic thats main reason Commented May 24, 2017 at 10:25

2 Answers 2

9

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

var myButton = Button(this);

'this' will be the activity.

Sign up to request clarification or add additional context in comments.

1 Comment

i want to add button to another view. how to add them
1

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)


}

2 Comments

Please show where mainLayout coming from.
@zeeshan from something like val mainLayout= findViewById<ConstraintLayout>(R.id.mainLayout) depending on the view in your layout XML file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.