2017-03-05 26 views
0

我是一名初学者级别的android开发人员,正在创建一个基本的待办事项列表应用程序。该应用程序包含带有彩色圆圈的自定义列表视图以显示优先级,标题和复选框以在用户完成时检查和删除项目。应用程序使用SQLite数据库存储这些待办事项,并使用Loader来检索数据。android:如何用复选框删除ListView项目?

我想要的是一旦复选框被选中,从列表中删除项目。

我试图实现适配器类这样的删除任务(也试过动画删除。):

CheckBox itemCheck = (CheckBox)view.findViewById(R.id.todo_checked); 
    itemCheck.setChecked(false); 
    itemCheck.setTag(priority); 
    itemCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if(isChecked){ 
       int idIndex = cursor.getColumnIndex(TodoTable.ID); 
       final int id = cursor.getInt(idIndex); 
       final Uri uriTodDelete = ContentUris.withAppendedId(TodoTable.TABLE_URI,id); 
       Animation slideOut = AnimationUtils.loadAnimation(context,android.R.anim.slide_out_right); 
       slideOut.setAnimationListener(new Animation.AnimationListener() { 
        @Override 
        public void onAnimationStart(Animation animation) { 

        } 

        @Override 
        public void onAnimationEnd(Animation animation) { 
         context.getContentResolver().delete(uriTodDelete,null,null); 


        } 

        @Override 
        public void onAnimationRepeat(Animation animation) { 

        } 
       }); 
       view.startAnimation(slideOut); 

的问题是,每当我删除列表视图中的首个项目,该项目正下方它会被删除。但是如果我从底部删除它可以正常工作。

我该如何解决这个问题?任何帮助将不胜感激。

P.SourceResolver类的delete方法正在处理notifyDataSetChanged()方法。

+0

请张贴您的适配器代码以帮助其他人诊断问题。 –

回答

0

胡乱猜测,你是不是将光标移动到相关行 所以光标在位置X,但你可以点击-on listview-上项目的位置Y。

因此您需要在尝试获取ID值之前将光标移到相关位置。

我想你是在getView()这个代码?因为您正在使用适配器。

你需要利用位置参数的getView()如下决议:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 

    : 
    : 
    if(isChecked){ 
     cursor.moveToPosition(position); 
     int idIndex = cursor.getColumnIndex(TodoTable.ID); 
     final int id = cursor.getInt(idIndex); 
     : 
     : 
    } 

    : 
    : 
} 

你还需要确保光标正在re query否则一旦你删除列表中的项目,你可能会得到一些问题的立场 - 我认为这是自动处理,如果您使用的是cursor adapter? 只是仔细检查。