It was packed for about 2 months, so a memorandum
IDE:Android Studio 3.4 Language: Java
Xperia XZ3 (used for debugging the actual machine) OS is Android 9 (API Level 28)
Prevent the CheckBox in the ListView from changing its check state by scrolling.
In the getView method that processes the elements displayed in ListView, re-paste the listener of CheckBox of ListView and use the position of the argument of getView in the onCheckedChanged method to get the item again.
Although it is not shown in the code below
ArrayAdapter
The following is a successful example.
ListAdapter.java
//ListItem is a self-made class of elements to be displayed in ListView.
private ListItem item;
//Omitted ~~~~~~~~~~~~
public View getView (final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
//If there is nothing in convertView, create a new one.
convertView = mInflater.inflate(mResId, parent, false);
//Get the element of each item in the list.
holder = new ViewHolder();
holder.isActive = convertView.findViewById(R.id.alarm_active);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
//Get an instance of the item to display in the list view.
item = getItem(position);
//Peel off the listener.
holder.isActive.setOnCheckedChangeListener(null);
//Item obtained from position on the element(Instance of homebrew class)Is assigned to the element.
holder.isActive.setChecked(item.isActive());
//Paste the listener.
holder.isActive.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged (CompoundButton cb, boolean isChecked) {
ListItem listItem = getItem(position);
//Null check for warning
if (listItem != null){
listItem.setActive(isChecked);
}
}
});
return convertView;
}
The important thing here is in the ** onCheckedChanged ** method in the anonymous class
ListItem listItem = getItem(position);
It is a process called.
This process is to reflect the check status in the list element (self-made class),
Delete this part just because it is already done like ʻitem = getItem (position); If you do something like ʻitem.setActive (isChecked);
, it will not work properly.
Recommended Posts