在ListView中显示列表中的变量

时间:2012-06-02 21:57:40

标签: android list listview arraylist

我有一份地点列表

ArrayList<Location> locationList;

每个位置都包含名称,地址,说明等信息... 我只想在每一行中显示名称,以便您可以选择要在新意图中接收更多信息的位置。

我设法使用以下代码在ListView中显示字符串:

    locationNames= new String[]{"I","am", "a", "ListView"};

    setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem,
            locationNames));
    ListView locationListview;
    locationListview = getListView();
    locationListview.setTextFilterEnabled(true);

到目前为止这是有效的,但我无法在此listView中显示List的内容,也无法询问有关所单击行的更多信息。

我考虑过读取列表的第一个元素,将它们保存在字符串数组中。 如果要单击它们以获取更多信息,这将导致问题。

这样做的最佳方式是什么?

诚恳, Wolfen的

2 个答案:

答案 0 :(得分:1)

我不确定这是你要求的。

将位置名称放在String数组中,如下所示:

String names[] = new String[locationList.size()];

int i=0;
for( Location loc:locationList )
{
    names[i] = loc.name;
    i++;
}

然后在适配器中使用此数组names而不是locationNames

setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, names));

最后在列表中设置一个监听器以获取项目点击事件:

    locationListview.setOnItemClickListener( new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        {
            // Read your location information using the position parameter
            Location l = locationList.get( position );

            // Show the rest of the location info ...

        }               
    });

答案 1 :(得分:0)

这样的事情:

Location[] locationArray = new Location[locationList.size()];
locationList.toArray(locationArray); 
setListAdapter(new ArrayAdapter<Location>(this, R.layout.singleitem,
locationArray));

并覆盖Location的 toString()方法以返回该位置的名称。如果您没有自己创建Location类,则需要创建一个子类来覆盖toString()方法。