有没有任何可能的方法可以使用只包含特定项目的setAdapter在listview中添加项目?例如,我想在列表视图中添加一个仅包含日期"2015年2月15日"的项目。
以下代码:
final ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
SimpleDateFormat formatdate = new SimpleDateFormat("MMM. dd, yyyy");
String selecdate = formatdate.format(date);
if (eventDates.contains(selecdate)) {
myList.setAdapter(adapter); //these line I want only to add items in listview which contains the value of 'selectdate'
}
else {
myList.setAdapter(null);
}
SimpleAdapter
用于静态数据。由于您希望动态筛选数据,因此应该实现一个自定义适配器来完成此操作。然而,一个廉价的解决方案是在设置适配器之前过滤数据。像这样:
ListView myList = (ListView) findViewById(android.R.id.list);
SimpleDateFormat formatdate = new SimpleDateFormat("MMM. dd, yyyy");
String selecdate = formatdate.format(date);
// Filter selected events
List<Map<String, Object>> filteredEventsList = new ArrayList<Map<String, Object>>();
for (Map<STring, Object> row : eventsList) {
if (row should be shown) {
filteredEventsList.add(row);
}
}
final ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, filteredEventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
myList.setAdapter(adapter);