简体   繁体   中英

How do I specify which string of an ArrayAdapter to use for a ListFragment?

I have a simple ListFragment to display a list of custom objects.

MyListFragment extends ListFragment

private ArrayList<CustomObject> mArrayOfCustomObject;
private ArrayAdapter<CustomObject> mAdapter;

mAdapter = new ArrayAdapter<CustomObject>(context,
    android.R.layout.simple_list_item1,
    mArrayOfCustomObject);
setListAdapter(mAdapter);

The problem is that I get a long list that looks like this:

com.example.CustomObject@40XXXXXX
com.example.CustomObject@40XXXXXX
com.example.CustomObject@40XXXXXX
com.example.CustomObject@40XXXXXX
....

I am doing it this way because I want to be able to click on an item and display more information about it. This is why I'm linking the adapter to a List<CustomObject> rather than List<String> .

I know that a List<String> would display it correctly, but then each item would just be a random string with no connection to it's CustomObject.

What's the best way to solve this?

Aside from creating your own custom Adapter,for an easy fix just override the toString() method in CustomObject and have it return something readable. When the Adapter you're using populates its rows, it calls toString() on your CustomObject then displays that result.

Say that you had a field in your CustomObject called timePassed

long timePassed = 100000l;
@Override
  public String toString()
  {
    return "Time passed: " + timePassed + " milliseconds";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM