删除列表视图条目

时间:2013-01-01 21:42:33

标签: android sql listview

我的问题是,在ListView /数据库中,只有最顶层的“评论”被删除,但我想,按下的“评论”会被删除。

@Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        datasource = new CommentsDataSource(this);
        datasource.open();

        List<Comment> values = datasource.getAllComments();

        // Use the SimpleCursorAdapter to show the
        // elements in a ListView
        ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
            android.R.layout.simple_list_item_1, values);
        setListAdapter(adapter);




        this.getListView().setClickable(true);
           this.getListView().setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                    Toast.makeText(MainActivity.this, "postion: " +    getListView().getSelectedItemPosition(), Toast.LENGTH_SHORT).show();

这是问题,即在getcount&gt; 0

                    ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
                    Comment comment = null;
                    if (getListAdapter().getCount() > 0) {
                        comment = (Comment) getListAdapter().getItem(0);
                        datasource.deleteComment(comment);
                        adapter.remove(comment);
                      }
                    return;
                }});
           }

1 个答案:

答案 0 :(得分:0)

使用getItem(0)总是会删除适配器中的第一项(因此也就是listview)。

如果要在单击时删除项目,请在onItemClick中使用以下代码。

Comment comment = (Comment) adapter.getItem(position);
datasource.deleteComment(comment);
adapter.remove(comment);

这就是它的全部内容。