0
我有一個需要4個參數的類。這個類叫做Item。我創建了一個ArrayList的List變量。然後我創建一個新的ListAdapter。我將此適配器設置爲主ListView。然後我將10個輸入添加到ArrayList中。這一切都工作,但當我嘗試將ArrayList項目添加到ListAdapter是給我一個錯誤說要添加Cast到方法。將列表添加到自定義適配器時出錯 - Android
這裏是我講的
final List <Item> tempList = new ArrayList <Item>();
mainListViewListAdapter = new ListAdapter(MainActivity.this, R.layout.main_list_item_layout, tempList);
// set mainListAdapter
mainListView.setAdapter(mainListViewListAdapter);
for (int x = 0; x < 10;x++){
tempList.add (new Item ("Example1","Example2","Example3","Example4"));
}
***HERE IS WHERE I GET THE ERROR AT addAll();***
mainListViewListAdapter.addAll(tempList);
mainListViewListAdapter設置爲ListAdapter的代碼,並mainListView設置爲ListView控件。
爲什麼要添加轉換到mainListViewListAdapter?我已經在另一個項目上運行這個代碼,我不必使用強制轉換。
爲了避免這種錯誤,您可以設置適配器之前,添加項目。使用addAll方法刪除行,如果用這種方式完全不重要。 – lub0v
好主意,但我需要在設置適配器後添加它們,因爲項目在活動期間被多次添加到listadapter – user2861085
我想出了答案。 'ListAdapter'需要在mainListViewListAdapter = new ListAdapter(MainActivity.this,R.layout.main_list_item_layout,tempList)之前;' – user2861085