I was trying to implement a simple list using a linearLayout and a scrollview so the idea was to basically have a List of models and inflate the item Layouts manually .. populate them with data and then add to the LinearLayout which is fine in theory but when I do it this way:
//for (item : List) addModelToView(item)
private fun addModelToView(model: Model) {
val linearLayout = binding.linearContainer
val item = activity?.layoutInflater?.inflate(R.layout.model_layout,linearLayout, true)
item?.findViewById<TextView>(R.id.textView10)?.text = model.name
item?.findViewById<TextView>(R.id.textView11)?.text = model.company
item?.findViewById<TextView>(R.id.textView12)?.text = model.size.toString()
}
but doing it this way only displays the Last item correctly while the rest of the items are there but with the default values of the xml layout .. like the following
So what exactly am I missing here? I tried inflating the item layouts manually and using ViewGroup.addView()
method with LayoutParams
and it worked just fine but I don't see how the two approaches are different
Your issue is return value of layoutInflater.inflate()
.
When you provide root and set attachToRoot
to true it returns the root itself - not the newly created view. This causes your view.findViewById
to essentially be linearLayout.findViewById
and that will always find and return the first set of views, regardless of haw many times you've performed the inflation.