Question

J'ai une application Android qui pose une question suivie par le numéro de x d'options. Chaque option contient une textview, ImageView et radio button.

La valeur de x (à savoir le nombre d'options) ne sont pas constantes. Je veux ajouter du contenu dynamique interface utilisateur pour satisfaire à cette exigence.

En ce moment j'ai écrit le code dans le xml de la mise en page pour afficher un maximum de 4 options. Si nombre d'options est 2 je masquer les options 3 et 4 à l'aide de quelque chose comme

tvoption1.setVisibility(View.GONE);
tvoption2.setVisibility(View.GONE);

Toutefois, ce n'est pas très évolutive. Quelqu'un peut-il me dire comment ajouter des options pour java dynamiquement. Ou est-il une meilleure approche?

Était-ce utile?

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top