【问题标题】:android:How to delete a ListView item with checkbox?android:如何删除带有复选框的ListView项目?
【发布时间】:2017-07-25 04:21:01
【问题描述】:

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

我正在尝试在选中复选框后立即从列表中删除该项目。

我尝试像这样在适配器类中实现删除任务(也尝试动画删除。):

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.S Content Resolver 类的 delete 方法正在处理 notifyDataSetChanged() 方法。

【问题讨论】:

  • 请发布您的适配器代码以帮助其他人诊断问题。

标签: android sqlite listview checkbox


【解决方案1】:

胡乱猜测,您没有将光标移动到相关行 所以光标在 pos x 但你可以点击 -on listview- on item at pos 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,这是自动处理的? 仔细检查一下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2012-12-11
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多