1

我有一个显示数据库记录的列表视图。列表视图中的每一行都有一个复选框。我如何能...

  1. 创建一个 toast 消息显示所选项目的值?
  2. 识别用户在列表视图中选择的记录?
  3. 遍历每个选定的项目并仅从数据库中删除列表视图中选定的行?

我一直在关注这个有用的教程://http://www.vogella.com/articles/AndroidSQLite/article.html

public class PhoneNumberDataBaseListView extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        NumbersDataSource datasource = new NumbersDataSource(this);
        datasource.open();
        String number = "123";
        datasource.createNumber(number);
        List<Number> values = datasource.getAllNumbers();
        ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
        setListAdapter(adapter);
    }

    public void deleteNumber() {
        NumbersDataSource datasource = new NumbersDataSource(this);
        datasource.open();
        ListView LV = (ListView) findViewById(android.R.id.list);
        List<Number> values = datasource.getAllNumbers();
        ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
        setListAdapter(adapter);

        SparseBooleanArray checkedItems = LV.getCheckedItemPositions();
        for (int i = 0; i < checkedItems.size(); i++) {
            if(checkedItems.valueAt(i)) {
                Number item = adapter.getItem(i);
                Toast t = Toast.makeText(this, item.getNumber().toString(), Toast.LENGTH_LONG);
                t.show();
             }  
        }
    }
4

1 回答 1

0

Method getCheckedItemPositions() returns SparseBooleanArray that indicates which items are checked (if item on specific position is checked, method valueAt(position) invoked on that array returns true). Class DBAdapter from tutorial you are following provides you with deleteTitle(long rowId) method which you should use to acheive what you want.Therefore your code should look more or less like this:

SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
    if(checkedItems.valueAt(i)) {
        db.deleteTitle(adapter.getItemId(i));
     }
}

Of course SimpleCursorAdapter and DBAdapter should be stored in object attributes so that you have access to them from both methods (onCreate and deleteRecord). By the way, View parameter passed to deleteRecord method is not needed.

于 2013-01-21T22:18:37.557 回答