'What's the cleanest way to create dynamic layout according to selected item in a spinner?
Im trying to figure out, what is the cleanest solution to arrange a layout according to the item selected in my spinner.
In my spinner i have values representing pace for running MAS (max aerobic speed) - 800m - 1500m - 5000m - 10 000m - Half marathon & Marathon and for each of those the layout displayed gonna change.
For example if it's MAS selected there will be time indicator for 100m-200m-400m-1000m and various percentage for those distance like 85% - 90% - 100% - 105% so close 16 label + value textview
If the item selected is marathon, there will be time indicator for 1000m - 2000m - 5k - 10k- 15k - half - 30k - 40k - 42k195 so only 0 textview
Would it be better to create a single layout and set visible/invisible textview according to my needs ?
Or having "hardcoded" layout that i returned according to the item selected ?
Hope i'm clear enough, i know that lot of things are possible but i'm really trying to be as clean as possible and i'm not satisfied with either solutions i've written above
Solution 1:[1]
I do not understand your UI but general approach is views differ a lot we put them in separate fragments/XMLs. Having separate views in XML is easier to read and develop. Performance wise it is faster to create views programmatically than inflating XMLs, but you are compromising readability.
- So if your screens differ a lot, you would need to show hide a lot of views, hence have a lot of code handling that in one place, I would go with different XMLs for each screen.
- If you need to show/hide 3-4 views, I would do it programmatically.
Solution 2:[2]
It would be great if you'll provide your UI. But in any cases you can choose one of next variants:
- XML layout;
- Creation views programmaticaly;
- ViewStub - an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime(good article about ViewStub here);
- Jetpack Compose - Android’s modern toolkit for building native UI(more here).
So, I can suggest you to use ViewStub or Jetpack Compose as more clean and modern approaches.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Torima |
| Solution 2 | Roman Chekashov |
