我目前正在使用一个简单的Android应用程序,该应用程序将允许用户使用复选框从sqlite DB中添加/删除/删除记录。 主要活动具有一个列表视图,该列表视图呈现来自运动适配器的对象。适配器从游标适配器扩展。 我遇到的问题是选择一个复选框,然后向下滚动列表,使该复选框不可见,状态丢失。 以下是我的主要活动和运动适配器的摘录:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbManager = new DBManager(this);
dbManager.open();
adapter = new ExerciseAdapter(this, dbManager.fetch());
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
public void deleteExercise(View view) {
for (int i = 0; i < adapter.getCount(); i++) {
CheckBox c = listView.getChildAt(i).findViewById(R.id.checkBox);
if (c.isChecked()) {
deleteIds.add(adapter.getItemId(i));
}
}
for (Long deleteId : deleteIds) {
dbManager.delete(deleteId);
adapter.update(dbManager.fetch());
}
}
ExerciseAdapter:
public class ExerciseAdapter extends CursorAdapter {
public ExerciseAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.exercise, parent, false);}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView exerciseTitle = view.findViewById(R.id.exerciseTitle);
TextView exerciseDesc = view.findViewById(R.id.exerciseDescription);
TextView exerciseDate = view.findViewById(R.id.exerciseDate);
// Extract properties from cursor
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String desc = cursor.getString(cursor.getColumnIndexOrThrow("description"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
// Populate fields with extracted properties
exerciseTitle.setText(title);
exerciseDesc.setText(String.valueOf(desc));
exerciseDate.setText(String.valueOf(date));
}
public void update(Cursor cursor) {
this.swapCursor(cursor);
this.notifyDataSetChanged();
}
}
这是采用的代码,因此除非没有其他选择,并且需要进行较大的更改,否则它们希望保持与现在相似的类。
谢谢。