【发布时间】:2016-05-11 15:16:41
【问题描述】:
我正在尝试使用复选框实现列表视图,以便在选中复选框时删除列表行。我正在用光标填充列表视图,这工作正常并且正在显示复选框。
我遇到的问题是弄清楚如何获取已选中框的行的_id。
谁能告诉我如何实现这样的东西
ListView 和 CheckBox
Cursor cursor = db.getAllItems();
//String[] columns = new String[] {db.KEY_NAME, db.KEY_CODE, db.KEY_ROWID};
String[] columns = new String[] {db.KEY_ITEM_NAME, db.KEY_MEASUREMENT, db.KEY_UNIT};
int[] to = new int[] {R.id.ingredientName, R.id.ingredientMeasurement, R.id.ingredientUnit};
final SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,R.layout.row4, cursor, columns, to, 0);
final ListView shoppingList = (ListView) findViewById(R.id.shoppingList);
shoppingList.setAdapter(myCursorAdapter);
CheckBox deleteCheck = (CheckBox)findViewById(R.id.checkBox1);
deleteCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (isChecked){
// How do I get the list item clicked to delete row?
}
}
});
XML - Row.4.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="@+id/ingredientName"
android:layout_width="wrap_content"
android:textColor="#000000"
android:layout_height="wrap_content"
android:padding="5dp"
android:hint="wewewe"/>
<TextView
android:id="@+id/ingredientMeasurement"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/ingredientName"
android:padding="5dp"
android:hint="fefefef"/>
<TextView
android:id="@+id/ingredientUnit"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/ingredientMeasurement"
android:padding="5dp"
android:hint="qqqqq"/>
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#fff"
android:text=""/>
</LinearLayout>
【问题讨论】:
-
好吧,您可以创建两种从列表视图中删除项目的方法,一种在适配器中,第二种在数据库中。
adapter.remove(item.getId(checkedId));并从数据库中调用第二个方法dataBase.remove(item.getId(checkedId));这就是您从适配器和数据库中删除项目的方式。 -
感谢回复,只有一个问题,
getId函数,这会得到该行的id还是数据库中实际的_id? -
getId函数将获取您在 listView 中选择的对象的指定 id。