简体   繁体   中英

How can I create a TextView for each element in a list in Android?

I am trying to create a textview in Android for each element in a list. How can I dynamically generate a textview for each element in the list?

I have tried using a for loop to iterate through the list and create a new textview for each element, but I am having trouble implementing this. Any help would be greatly appreciated.

You will normally use a RecycleView for this, but in certain scenarios you will add list manually.

You can simply create the TextView and add the properties to it, it is important that you include the LayoutParams so that the view can be rendered.

        val food = listOf("apple", "pie", "banana", "cookie")
        val linearLayout = findViewById<LinearLayout>(R.id.myList)

        food.forEach {
            TextView(this).apply {
                layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
                text = it
                linearLayout.addView(this)
            }
        }

keep in mind that LayoutParams needs to be the nested class of the respective ViewGroup , so if the parent is a LinearLayout , you should use LinearLayout.LayoutParams

If it is not a TextView but a view that you defined in your own XML layout (res/layout/my_custom_row.xml) you can use binding for it:

MyCustomRowBinding.inflate(layoutInflater, containerLayout, true).apply {
     nameTextView.text = item.name
}

you don't need to use viewGroup.addView() because inflater already adds the view when last parameter is true .

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