0

I have a button (add) that creates new buttons when pressed (up to 8). But when I try to refer to these buttons and add functionality, I am unable to find the ids' for them. How could I make and find ids' for these buttons?

Note: the button ids should be created automatically when (add) is pressed.

val LLayout: View = layout
    var currentId = 0


    add.setOnClickListener {
        val addedButton = Button(this)
        addedButton.text = written.text.toString()
        addedButton.id = currentId++
        addedButton.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        (LLayout as LinearLayout).addView(addedButton)
        //clearing text from EditText written
        written.text.clear()
    }
1

3 Answers 3

2

Instead of a unique id you can simply set tag property for each Button object and then find that button with that tag and define your functionality

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

Comments

1

You can generate an Id for each button using generateViewId() method.

 addedButton.id = generateViewId()

Also, Create a new Button every time the user clicks on add button. So you should do something like this:

add.setOnClickListener {
        val addedButton = Button(this)
        addedButton.text = written.text.toString()
        addedButton.id = generateViewId()
        addedButton.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        (LLayout as LinearLayout).addView(addedButton)
        //clearing text from EditText written
        written.text.clear()
    }

3 Comments

How can I reference the generated id later on. For example, if I want to make the button lead to a new activity, change color, Etc.
You can save the generated id or button in an array or list and can reference it later.
Could you show how to do this in your answer please?
0

For unique id you can set the (number of child view + 1) as id to the newly created Button.

Comments

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.