This is the tutorial that I followed使用自定义Listview适配器。我遇到的问题是,当我尝试清除适配器时,应用程序崩溃并抛出java.lang.UnsupportedOperationException
if(adapter != null) {
adapter.clear();
}
更新后的代码:
private void setListViewAdapterToDate(int month, int year, int dv)
{
if(summaryAdapter != null) {
summaryAdapter.clear();
}
setListView(month, year, dv);
summaryList.addAll(Arrays.asList(summary_data));
summaryAdapter = new SummaryAdapter(this.getActivity().getApplicationContext(), R.layout.listview_item_row, summaryList);
summaryAdapter.notifyDataSetChanged();
calendarSummary.setAdapter(summaryAdapter);
}
答案 0 :(得分:6)
环顾一下,似乎用数组初始化适配器是个问题。请参阅UnsupportedOperationException with ArrayAdapter.remove和Unable to modify ArrayAdapter in ListView: UnsupportedOperationException
尝试使用ArrayList
代替array
,如此
ArrayList<Weather> weather_data = new ArrayList<Weather>()
weather_data.add( new Weather(R.drawable.weather_cloudy, "Cloudy") );
// continue for the rest of your Weather items.
如果您感到懒惰,可以通过这种方式将array
转换为ArrayList
ArrayList<Weather> weatherList = new ArrayList<Weather>();
weatherList.addAll(Arrays.asList(weather_data));
要完成ArrayList
课程中WeatherAdapter
的转换,您需要删除Weather data[] = null;
及其所有引用(例如构造函数内部),因为ArrayAdapter
为您保存数据,您可以使用getItem
因此,在getView
函数内部,您需要将Weather weather = data[position];
更改为Weather weather = getItem(position);
<强>更新强> 使用
修改您的新代码private void setListViewAdapterToDate(int month, int year, int dv)
{
setListView(month, year, dv);
if(summaryAdapter != null) {
summaryAdapter.clear();
summaryAdapter.addAll( summaryList );
summaryAdapter.notifyDataSetChanged();
} else {
summaryList.addAll(Arrays.asList(summary_data));
summaryAdapter = new SummaryAdapter(this.getActivity().getApplicationContext(), R.layout.listview_item_row, summaryList);
}
calendarSummary.setAdapter(summaryAdapter);
}