Question

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?

Was it helpful?

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

OTHER TIPS

create your row layout separately, from the main xml

Get LayoutInflater service from context:

LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATE_SERVICE);

use following method to addview to main xml, I assume you have parent layout llParent in xml and you want to add items in this llPaent, from list list.

for(int i=0;i<list.size();i++)
{
     LinearLayout llView=(LinearLayout)inflater.inflate(R.layout.row);
     //get view id and set values
     TextView txt=(TextView)llView.findViewById(R.id.text);
}

A ListView is a good view for displaying several similar items. Here is a tutorial (Other views with adapters are good too, such as GridView or Gallery).
You will probably want to create your own adapter for the list, so you can display all three views (checkbox, image and text) as one item, but there are lots of examples on that available on the net as well as here on SO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top