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()
    }
Shagufta
  • 40
  • 5

3 Answers3

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

Masoud Badrmiran
  • 421
  • 2
  • 4
  • 11
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()
    }
Alpha 1
  • 4,118
  • 2
  • 17
  • 23
0

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