stressedkid
stressedkid

Reputation: 45

How to set a unique id to dynamically generated views in Kotlin for Android?

I have button that when pressed creates the following layout:

fun handleAddTally(view: View) {
    with(view as Button) {
        btn_count += 1

        val this_btn = view.resources.getResourceEntryName(id)
        var container_overall = LinearLayout(this@SecondActivity)
        container_overall.setOrientation(LinearLayout.VERTICAL)

        var container_inputs= LinearLayout(this@SecondActivity)
        container_inputs.setOrientation(LinearLayout.HORIZONTAL)
        var text_width= TextView(this@SecondActivity)
        text_width.setText("W:")
        var input_width= EditText(this@SecondActivity)
        text_width.setWidth(30)
        input_width.setWidth(90)
        input_width.id = width_count+btn_count
            }
}

I want to be able to generate multiple layouts like that of above but with each instances having a unique id. Would that be possible? If it is not, I would really appreciate a way to assign a unique identifier of any sort to each instances of the layout.

Upvotes: 0

Views: 1154

Answers (1)

Praveen
Praveen

Reputation: 3486

You can generate unique id dynamically for your views using View.generateViewId() function.

For you programmatically created layout or view, you can set id like this

container_overall.id = View.generateViewId()

Upvotes: 2

Related Questions