简体   繁体   中英

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM