0

I am wondering if it is possible to create UI elements dynamically in android apps without using xml or design? The number of elements and type of elements will be different based on the requirements I get from a json array. So, can I create buttons, textviews, etc in my activityClass file, without actually having them in my xml file??

if yes, then how complicated would it be? can you provide an example please?

Also, are there any libraries for android that I can use that would just dynamically create the fields for me based on types and number of fields as an input?

JJ S.
  • 84
  • 7
  • https://stackoverflow.com/a/26133978/2340813 explains creating views programmatically. You could also learn how to use RecyclerView + ViewHolder if you're planning on displaying a list of elements in a scrollable list driven by your json array. I would recommend CodePath's guide (https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView) as a resource. – MikeOscarEcho Mar 06 '20 at 21:14

1 Answers1

1

Yes. You just create the View objects using new, then add them to their parent layouts using .addView(newView). If necessary, add them with the correct LayoutParams object.

I will say that this is MUCH harder to write and debug than xml, so it should be done only if something absolutely has to be manual. Even if you are getting things from a JSON blob, its best to make as much of that just deciding what xml to inflate as possible.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • thank you! the thing is that I don't know how many fields are there going to be until I parse the json! Else I would've made it in the xml. Any way around this to make it easier? I know I can hide or display fields, but there can be multiple fields of same type and i don't know what order to display in, until i get the json...please help T-T – JJ S. Mar 06 '20 at 22:30
  • 1
    That is a valid reason to use dynamic views. What you can do to simplify it depends on your usecase. If the content is variable but the style isn't I'd make use of styles to minimize the amount of configuration code you need to write. I'd also pair common views used together into custom views you can inflate via xml, rather than making them specify every view in the layout. – Gabe Sechan Mar 08 '20 at 03:02