我的ListView项包含TextView和LinearLayout。 LinearLayout包含动态生成的CheckBoxes,每个列表项中的复选框数可以不同。我想在屏幕上滚动项目时保存复选框的状态,然后将其向后滚动以进行对焦。现在它没有被保存。这是我的代码,你能告诉我我做错了吗?
public class ListAdapter extends ArrayAdapter<BaseModel> {
private ArrayList<CheckboxModel> mCheckboxModels;
private static class ViewHolder {
TextView mName;
LinearLayout mLinearLayout;
}
public ListAdapter(Context context, ArrayList<BaseModel> baseModels) {
super(context, 0, baseModels);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
final BaseModel currentBaseModel = getItem(position);
mCheckboxModels = new ArrayList<>();
View currentRow = convertView;
ViewHolder viewHolder;
if (currentRow == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
currentRow = inflater.inflate(R.layout.list_item, parent, false);
viewHolder.mName = (TextView) currentRow.findViewById(R.id.idTextView);
viewHolder.mLinearLayout = (LinearLayout) currentRow.findViewById(R.id.idCheckboxLinearLayout);
currentRow.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) currentRow.getTag();
}
if (currentBaseModel != null) {
viewHolder.mName.setText(currentBaseModel.getName());
viewHolder.mLinearLayout.removeAllViewsInLayout();
int numOfButtons = currentBaseModel.getNumOfButtons();
for (int i = 0; i < numOfButtons; i++) {
mCheckboxModels.add(new CheckboxModel(new CheckBox(getContext()), false));
currentBaseModel.setCheckboxModels(mCheckboxModels);
viewHolder.mLinearLayout.addView(currentBaseModel.getCheckboxModels().get(i).getCheckBox());
final int j = i;
currentBaseModel.getCheckboxModels().get(i).getCheckBox().setOnCheckedChangeListener(
new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
currentBaseModel.getCheckboxModels().get(j).setChecked(isChecked);
}
});
currentBaseModel.getCheckboxModels().get(i).getCheckBox()
.setChecked(currentBaseModel.getCheckboxModels().get(i).isChecked());
}
}
return currentRow;
}
}
答案 0 :(得分:0)
不要做mCheckboxModels = new ArrayList&lt;&gt;();在getView()
中你必须这样做:
private ArrayList mCheckboxModels = new ArrayList&lt;&gt;()