0

私の問題は、ListView/Database で一番上の「コメント」のみが削除されることですが、押された「コメント」が削除されることです。

@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 > 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;
                }});
           }
4

1 に答える 1

0

getItem(0) を使用すると、常にアダプター (したがってリストビュー) の最初の項目が削除されます。

アイテムがクリックされたときにアイテムを削除する場合は、onItemClick で次のコードを使用します。

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

それだけです。

于 2013-01-01T22:11:34.800 に答える