How to put items from a Listview in strings.xml

3

I have a custom listview, with images and text:

private void createListView() {
    //Criamos nossa lista que preenchera o ListView
    itens = new ArrayList<ItemListView>();
    ItemListView item1 = new ItemListView("Alimentacao", R.drawable.alimentacao);
    ItemListView item2 = new ItemListView("Esporte", R.drawable.esporte);
    ItemListView item3 = new ItemListView("Saude", R.drawable.saude);


    itens.add(item1);
    itens.add(item2);
    itens.add(item3);


    //Cria o adapter
    adapterListView = new AdapterListView(this, itens);

    //Define o Adapter
    listView.setAdapter(adapterListView);
    //Cor quando a lista é selecionada para ralagem.
    listView.setCacheColorHint(Color.TRANSPARENT);
}

There are many items. The best way to work would be to pass the string.xml to the item? how to call the item?

    
asked by anonymous 25.11.2014 / 01:40

1 answer

4

Exactly, the best way is to use string-array within strings.xml .

You would have an element, within strings.xml , with the declaration of your array:

<string-array name="categorias">
    <item>Alimentacao</item>
    <item>Esporte</item>
    <!-- Demais String's -->
</string>

To use just use the getStringArray method of Resources .

For example:

String[] categorias = getResources().getStringArray(R.array.categorias);

For Drawable's , you can create another array within the same file just by storing the suffix:

<string-array name="categorias_drawable">
    <item>alimentacao</item>
    <item>esporte</item>
    <!-- Demais Drawables -->
</string>

And access using getIdentifier of class Resources to retrieve id of Drawable :

int idDrawable = getResources().getIdentifier(nomeDoDrawable, "drawable", this.getPackageName());

The idDrawable will contain the same value as R.drawable.nomeDoDrawable .

To use the two solutions with the template class, just retrieve the two array's and iterate over them and create the items:

String[] categorias = getResources().getStringArray(R.array.categorias);
String[] drawableCategorias = getResources().getStringArray(R.array.categorias_drawable);

for(int i = 0; i < categorias.length; ++i) {
    itens.add(new ItemListView(categorias[i], getResources().getIdentifier(drawableCategorias[i], "drawable", this.getPackageName()));
}

// itens possui a lista as classes do modelo populada
// com os dados do strings.xml
    
25.11.2014 / 01:56