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.
CodePudding user response:
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
.