简体   繁体   English

如何指定要用于ListFragment的ArrayAdapter的字符串?

[英]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. 我有一个简单的ListFragment来显示自定义对象的列表。

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> . 这就是为什么我将适配器链接到List<CustomObject>而不是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. 我知道List<String>可以正确显示它,但是每个项目只是一个随机字符串,与它的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. 除了创建自己的自定义适配器外,为简便CustomObject ,只需重写CustomObjecttoString()方法并使其返回可读的内容即可。 When the Adapter you're using populates its rows, it calls toString() on your CustomObject then displays that result. 当您使用的适配器填充其行时,它将在CustomObject上调用toString() ,然后显示该结果。

Say that you had a field in your CustomObject called timePassed 假设您的CustomObject有一个名为timePassed的字段

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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