android - 滚动时自动检查列表视图中的开关
问题描述
我知道这个问题与这个问题重复
滚动时列表视图中的开关会自动检查 android但答案对我不起作用
当我滚动浏览列表视图开关自动检查时,我遇到了同样的问题。如果数据等于“1”,则我的逻辑设置为打开,该数据从数据库中检索并且工作正常,但是当我滚动浏览列表时,所有开关都会被检查。
这是我的代码
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(null==view){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.list_item,null);
}
final ApplicationInfo data = appList.get(position);
if(null !=data){
final SwitchCompat appName = (SwitchCompat)view.findViewById(R.id.appName);
ImageView iconView = (ImageView)view.findViewById(R.id.app_icon);
//Read Data
dbHelper db = new dbHelper(context);
SQLiteDatabase database1 = db.getReadableDatabase();
Cursor cursor = database1.rawQuery("select isLocked from apps where package='"+appList.get(position).packageName+"'",null);
if(cursor !=null){
cursor.moveToFirst();
if(cursor.getInt(0) == 1){
appName.setChecked(true);
}
}
appName.setText(data.loadLabel(packageManager));
iconView.setImageDrawable(data.loadIcon(packageManager));
appName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
//appList.get(position).packageName
dbHelper dbHelper = new dbHelper(context);
SQLiteDatabase database = dbHelper.getWritableDatabase();
database.execSQL("update apps set 'isLocked'=1 where package='"+appList.get(position).packageName+"'");
}else {
dbHelper dbHelper = new dbHelper(context);
SQLiteDatabase database = dbHelper.getWritableDatabase();
database.execSQL("update apps set 'isLocked'=0 where package='"+appList.get(position).packageName+"'");
}
}
});
}
return view;
}
解决方案
在ListView
中,项目在滚动时被重用。如果复选框已被选中,则需要在使用前取消选中。
采用:
if(cursor.getInt(0) == 1){
appName.setChecked(true);
} else {
appName.setChecked(false);
}
代替
if(cursor.getInt(0) == 1){
appName.setChecked(true);
}
或在执行其他任务之前重置/取消选中复选框:
View view = convertView;
if(null==view){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.list_item,null);
}
final SwitchCompat appName = (SwitchCompat)view.findViewById(R.id.appName);
appName.setOnCheckedChangeListener(null);
appName.setChecked(false);
final ApplicationInfo data = appList.get(position);
if(null !=data){
// your code.
}
推荐阅读
- android - 如何在 Android Firefox 中修改特定网站的权限设置?
- javascript - 重定向到页面上的特定 DIV
- excel - Excel - 使用行条件返回列数组中前 n 个值的列标题
- python-3.x - 我怎样才能让我的小部件在 Kivy 中移动?
- apache-spark - 如何在pyspark中的窗口上乘以行?
- java - 如何使用 IntelliJ 在我的 java 应用程序中运行多个使用者
- .net - 在 MSTest 中的每个测试用例之后清除所有静态数据
- sql-server - 作业正常工作但 tempdb 未修改
- javascript - 如何将值从模板传递到 ts 函数
- python - Flask-mail 正在尝试使用 localhost 作为邮件服务器,而不是配置的 SMTP 服务器