我找到了一个关于从 android 的数据库中填充listView的示例,它运行良好,但是我想向这个应用程序添加一些功能,我想在我的listview中的每个项目旁边放置一个复选框,并且当用户检查每个项目时项目,他将能够通过按确认按钮删除该项目。我已经把这些行启用了多项选择,但复选框没有出现,我不知道如何删除选定的项目!
ListView lstView = getListView();
lstView.setChoiceMode(2);
public void onListItemClick(
ListView parent, View v, int position, long id)
{
//---toggle the check displayed next to the item---
parent.setItemChecked(position, parent.isItemChecked(position));
}
你能帮我解决我的问题吗?
这是我的代码:
package com.saigmn;
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DataListView extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
////----------------------
ListView lstView = getListView();
//lstView.setChoiceMode(0); //CHOICE_MODE_NONE
//lstView.setChoiceMode(1); //CHOICE_MODE_SINGLE
lstView.setChoiceMode(2);
// setListAdapter(new ArrayAdapter<String>(this,
// android.R.layout.activity_list_item));
}
//--------------------------------
public void onListItemClick(
ListView parent, View v, int position, long id)
{
//---toggle the check displayed next to the item---
parent.setItemChecked(position, parent.isItemChecked(position));
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
这是示例的链接