我很难弄清楚这一点。
我有一个带有 CursorAdapter 的 ListView ,如果项目离开屏幕,开关会自行重置。我在开关上设置了一个监听器 onCheckedChangeListener,它触发通过托管片段实现的监听器,该片段更新数据库表中的字段并重新查询整个事物(contentResolver.notifyChange())。
我知道这是复选框的常见问题,但我仍然无法让它工作。
public class FilterCursorAdapter extends CursorAdapter {
public interface OnSwitchToggledListener {
public void onSwitchToggled(int id, boolean isActivated);
}
private OnSwitchToggledListener listener;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = layoutInflater.inflate(R.layout.filter_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.keywordTextView = (TextView) view.findViewById(R.id.keyword_text_view);
holder.cathegoryTextView = (TextView) view.findViewById(R.id.cathegory_text_view);
holder.activateSwitch = (Switch) view.findViewById(R.id.switch_activate);
view.setTag(holder);
return view;
}
public void bindView(View row, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) row.getTag();
holder.keywordTextView.setText(cursor.getString(cursor.getColumnIndex(ArticleProvider.COLUMN_KEYOWRD)));
final int id = cursor.getInt(cursor.getColumnIndex(ArticleProvider.COLUMN_FILTER_ID));
String cathegory = cursor.getString(cursor.getColumnIndex(ArticleProvider.COLUMN_CATHEGORY));
int isActivated = cursor.getInt(cursor.getColumnIndex(ArticleProvider.COLUMN_ACTIVATED));
holder.cathegoryTextView.setText(string);
holder.activateSwitch.setChecked(isActivated == 1);
holder.activateSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listener.onSwitchToggled(id, isChecked);
}
});
}
private class ViewHolder {
public TextView keywordTextView;
public TextView cathegoryTextView;
public Switch activateSwitch;
}
}
public class FilterListFragment extends SherlockListFragment implements LoaderCallbacks<Cursor>, OnSwitchToggledListener {
@Override
public void onSwitchToggled(int id, boolean isActivated) {
Log.d(MainActivity.TAG, "ID: " + id + " isActivated: " + isActivated);
ContentValues values = new ContentValues();
values.put(ArticleProvider.COLUMN_ACTIVATED, isActivated);
resolver.update(ArticleProvider.FILTERS_URI, values, ArticleProvider.COLUMN_FILTER_ID + "=" + id, null);
}
}
从日志看来,bindView 中的 setOnCheckedChangeListener 侦听器会自行触发。
我该如何解决这个问题?另外我想指出我正在使用 SwitchCompatLibrary ( https://github.com/ankri/SwitchCompatLibrary )
谢谢!