I have a ListView with toggleButton in each row. When the toggleButton of a row is checked, I noticed that when I scroll down the ListView, every first out of 10 rows will also be checked.
How to ensure that only the selected row's toggleButton is checked? Here is my ArrayAdapter:
class AppListAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> applicationInfoList;
private Context context;
private PackageManager packageManager;
public AppListAdapter(Context context, int resource,
List<ApplicationInfo> objects) {
super(context, resource, objects);
this.context = context;
this.applicationInfoList = objects;
packageManager = context.getPackageManager();
}
@Override
public int getCount() {
return ((null != applicationInfoList) ?
applicationInfoList.size() : 0);
}
@Override
public ApplicationInfo getItem(int position) {
return ((null != applicationInfoList) ?
applicationInfoList.get(position) : null);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(null == view) {
view = layoutInflater.inflate(R.layout.row_application, null);
}
final ApplicationInfo data = applicationInfoList.get(position);
if(null != data) {
CardView rowLayout = (CardView) view.findViewById(R.id.row_layout);
TextView appName = (TextView) view.findViewById(R.id.row_app_name);
ImageView iconView = (ImageView) view.findViewById(R.id.row_app_icon);
ToggleButton toggleButton = (ToggleButton) view.findViewById(R.id.row_toggle_lock);
appName.setText(data.loadLabel(packageManager));
iconView.setImageDrawable(data.loadIcon(packageManager));
checkToggleStatus(toggleButton, rowLayout, data);
}
return view;
}
private void setToggleButton(ToggleButton toggleLock, ApplicationInfo data) {
if(toggleLock.isChecked()) {
toggleLock.setChecked(false);
applicationLocked.remove(data);
} else if(!toggleLock.isChecked()) {
toggleLock.setChecked(true);
applicationLocked.add(data);
}
}
// This method updates the lock status of each application and
// pop-up dialog that allows users to set start and end date to lock the application.
private void checkToggleStatus(final ToggleButton toggleLock,
final CardView rowLayout, final ApplicationInfo data) {
rowLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
appDatabase.setDefaultLockStatus(appDatabase, data.packageName);
Animation rotate360 = AnimationUtils.loadAnimation(context, R.anim.shake);
toggleLock.startAnimation(rotate360);
setToggleButton(toggleLock, data);
}
});
}
}