我无法搞清楚这个。
我有一个带有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)
谢谢!
答案 0 :(得分:1)
如果您遇到此问题,则需要在再次设置之前添加删除侦听器
holder.activateSwitch.setOnCheckedChangeListener(null)
答案 1 :(得分:0)
今天我遇到同样的问题大约三个小时。一旦它离开屏幕,它就改变了。所以,我最终放弃了onCheckedChanged
听众,而是使用了:
mySwitch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "isChecked:");
}
});
现在它完美无缺。