I have a LinearLayout with vertical orientation as parent, I want to add some view programmatically multiple times to this parent. Right now I am inflating the child every time getting new references to every UI element before adding to parent. This doesn't seem to be very efficient, is there any better way of doing this.
Current code I am using is below, If I inflate only once before for loop I get runtime error "he specified child already has a parent. You must call removeView() on the child's parent first."
LayoutInflater inflator = LayoutInflater.from(getBaseContext());
LinearLayout parentPanel = findViewById(R.id.parent_pannel);
ArrayList<String> myList = getData();
for(String data : myList) {
// inflate child
View item = inflator.inflate(R.layout.list_item, null);
// initialize review UI
TextView dataText = (TextView) item.findViewById(R.id.data);
// set data
dataText.setText(data);
// add child
parentPanel.addView(item);
}
Inflating multiple times cannot be done the same way doing it in single shot. Hope this works
This will work, at the least worked me
Did you actually check if inflate is slow? As far as I know, inflating view is very fast (almost as fast as creating views manually).
It might be surprising for you to hear but inflate in fact does not parse the XMLs at all. XMLs for layout are parsed and pre-processed at compile time - they are stored in a binary form which makes view inflation very efficient (that's why you cannot inflate a view from an XML generated at runtime).
I'm not sure what your view is but have you creating it manually over inflating the XML:
But yeah your clearly attempting something that has been done for you with Simple ListView & API
You can't, even if you try to create a
new view
from the oldview
object the object will be passed by reference not value, and hence you will got an Exception as the childAlreadyHasParent, and so, the only way is to put theview
into afor loop
with the number of times you want it to be inflated, and this loop must contain the creating process from beginning not only the inflating lines.