androiduser-interfacedynamic-ui

Dynamically add UI content in android


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?


Solution

  • A View can be added at runtime by using the inflater like this:

    LinearLayout linearLayout = (LinearLayout)inflater.inflate(R.layout.news_categories_item, null);
    
    TextView categoryValueTextView = (TextView)linearLayout.findViewById(R.id.news_category_item_value);
    
    mMainLinearLayout.addView(categoryValueTextView);
    

    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().