Question

I have an array of class "EditableListItem" each containing a string resource id. I want to create a list with the values of all these strings. The problem is that the items on my list end up showing the resource ID instead of the actual string.

Class EditableListItem:

public class EditableListItem {
    private int title_id;

    public EditableListItem(int title_id) {
        this.title_id = title_id;
    }
    //...
}

My List Activity:

    // Instantiate the list of samples.
    EditableListItem[] allItems = new EditableListItem[]{
            new EditableListItem(R.string.dialer),
            new EditableListItem(R.string.clock)
    };

    setListAdapter(new ArrayAdapter<EditableListItem>(this, android.R.layout.simple_list_item_1, android.R.id.text1, allItems));

How can I make my List show the String values instead of their IDs?

Was it helpful?

Solution

ArrayAdapter will use .toString() method to show the text.

Override it and use getString(title_id) to get the string (You will need the context).

You could:

  • Create a private field String stringRapp
  • Edit constructor to take a Context
  • Use this context and do stringRapp = context.getString(title_id);

If you are are sure resource ID never changes and will reference to the same string always.

If not:

  • Take Context from constructor
  • Save it in a field Context context
  • In .toString() method, return context.getString(title_id)

OTHER TIPS

You can use

getResources().getString(R.string.yourstring)

to get the String value of a String-resource.

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