I have an android app which asks a question followed by x number of options.
Each option contains a textview, ImageView and a radio button.
The value of x (i.e. the number of options) is not constant. I want to dynamically add UI content to satisfy this requirement.
At the moment I have written the code in the layout’s xml to display a maximum of 4 options. If number of options is 2 I hide the options 3 and 4 using something like
tvoption1.setVisibility(View.GONE);
tvoption2.setVisibility(View.GONE);
However this is not very scalable. Can anyone tell me how to add options for java dynamically. Or is there a better approach?
A
Viewcan be added at runtime by using the inflater like this:In this example, a LinearLayout containing a TextView is inflated. A reference to the constituent TextView is then obtained, and the TextView is dynamically added (at runtime) to the main linear layout (
mMainLinearLayout).The inflater object may be obtained in an Activity by using
getLayoutInflater().