Deleting checked ListView items

六眼飞鱼酱① 提交于 2019-12-10 11:51:15

问题


I'm trying to delete ListView items that are checked. It works if there is only one item checked but if there are two or three then the app force closes. On the error log it says:

E/AndroidRuntime(2173): java.lang.IndexOutOfBoundsException: Invalid location 2, size is 2

When having three items on the list and deleting 2. Can anyone help with correcting this error? Here is the code:

    public void delete() {
    btnDelete = (Button) findViewById(R.id.btnDelete);
    btnDelete.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            for (int i = 0; i < list.getChildCount(); i++) {
                View view = list.getChildAt(i);

                 CheckedTextView cv = (CheckedTextView) view.findViewById(R.id.checkList);
                 if(cv.isChecked()){
                    Log.i("DELETE", adapter.getItem(i).toString()+"   "+cv.toString());

                     adapter.remove(adapter.getItem(i));
                 }
                 adapter.notifyDataSetChanged();

            }
           Toast.makeText(getApplicationContext(), "Selected Items Cleared", Toast.LENGTH_SHORT).show();
       }
    });
   }

回答1:


The problem is with your for loop. you are iterating list view in the for loop by list.getChildCount() which is not correct read the Api doc correctly, replace it with adapter.getCount(); it will solve the problem.



来源:https://stackoverflow.com/questions/10418764/deleting-checked-listview-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!