I have a list view that contains a large number of items.. each item may contain two, three, four or may be five TextViews.. Without using expandable ListView.. which one is better and why.. Using XML file as view container with number of TextViews equal to the maximum number needed (using findViewById...) or adding the view by java code (myLinearLayout.add(new TextView())) .. the basic question is "which one is better for memory and speed" ? Why most of the applications use XML file for views ??
2 Answers
As per you question you said there is a two option for view initialization and which one is better so we have two options.
Option 1 :: Load view by XML.
Option 2 :: By doing this (myLinearLayout.add(new TextView()))
****Ans :: Option 1 is best.****
Because if we are using Option 2 than every time when we scroll listview it will create TextView dynamically which will definitely affect Performance of you List and it will consup more memory as dynamically we are creating TextView for every row.
Above limitation can be removed by using XML for view initialization.use ViewHolder Pattern for you Listview which is the best option in terms of Memory and speed as in this pattern we are reusing the views. Please check bellow link for more information about why ViewHolder Pattern is the best option.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html

- 143
- 5
-
You can and should use the ViewHolder pattern for either xml or code layouts. Moreover, when an xml gets inflated, the views will also have to be created dynamically, the difference is just that you have the _additional_ effort of parsing the xml. – FD_ Feb 07 '14 at 08:27
XML is the default/standard way to create layouts on Android. Usually we only create layouts in JAVA when it can be dynamic. In case of a static layout, just use an xml layout and then retrieve the view using view.findViewById(id) method

- 1,633
- 4
- 22
- 58