How to put items from a Listview into strings.xml

Asked

Viewed 1,085 times

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);
}

That’s a lot of items. The best way to work would be to pass the string.xml the item ? how to call the item?

1 answer

4


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

You would have an element within the 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 method getStringArray of Resources.

For example:

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

In the case of 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 the getIdentifier class Resources to recover the 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 model 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
  • But I did not understand how it looks in my project, q I use a model class, which receives the Item and Image, as it would look in my case? Itemlistview is the class I created, in case I would no longer use it?

  • It worked mann!! , thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.