调用.notifyDataSetChanged()时,我的适配器出现问题。它显示错误的项目
问题:
我在ArrayList
中保存了3个项目:项目1,项目2和项目3.当我使用.remove(Index)
删除项目1时,项目1被删除,但在调用{{1}之后我的notifyDataSetChanged()
显示:第1项和第2项,最后一项未显示,即使我的ListView
仅包含第2项和第3项。
下面的代码和输出:
ArrayList
删除前记录输出:
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int indexToDelete = i;
Log.i("indexToDelete", Integer.toString(i));
for (int ji = 0; ji < items.size(); ji ++ ) {
Log.i("ItemInside",items.get(ji).getItemName());
}
AlertDialog.Builder builder = new AlertDialog.Builder(UserSimplePlusNoteActivity.this);
builder.setTitle("Do you want to delete this note?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Item toDelete = items.get(indexToDelete);
String noteToDelete = toDelete.getItemName();
items.remove(indexToDelete);
for (int ji = 0; ji < items.size(); ji ++ ) {
Log.i("ItemInside2",items.get(ji).getItemName());
}
customAdapter.notifyDataSetChanged();
删除后:
03-29 14:00:19.118 23457-23457/com.example.user.testingapp I/indexToDelete: 0
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 1
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 2
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 3
这是我的适配器和项目:
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 2
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 3
档案:
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Item> items;
public CustomAdapter(Context context, ArrayList<Item> items) {
this.context = context;
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i) {
return items.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if(view == null) {
view = LayoutInflater.from(context).inflate(R.layout.custom_adapter, parent, false);
Item currentItem = (Item) getItem(position);
TextView textViewItemName = view.findViewById(R.id.titleID);
TextView textViewItemDescription = view.findViewById(R.id.detailID);
ImageView imageView = view.findViewById(R.id.imgID);
textViewItemName.setText(currentItem.getItemName());
textViewItemDescription.setText(currentItem.getItemDescription());
switch (currentItem.getPriority()) {
case 1:
break;
case 2:
imageView.setImageResource(R.drawable.priority_urgent_icon);
break;
case 3:
imageView.setImageResource(R.drawable.priority_important_icon);
break;
default:
Log.i("Ok", "Something strange happend");
}
}
return view;
}
}
答案 0 :(得分:0)
在这种情况下似乎notifyDataSetChanged()
没有正确刷新。使用新customAdapter
刷新items
并将其设置为listView,但notifyDataSetChanged()
之前的这两行仍然可以解决问题:
customAdapter = new CustomAdapter(getApplicationContext(), items);
listView.setAdapter(customAdapter);