I have following code:
public class MyListAdapter extends BaseAdapter {
private final List<MyClass> mItems = new ArrayList<MyClass>();
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
final MyClass myItem = mItems.get(position);
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.my_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.cbView = (CheckBox) rowView.findViewById(R.id.cbCheckBox);
viewHolder.cbView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
myItem.setState(isChecked);
}
});
rowView.setTag(viewHolder);
}
I'm very uncomfortable with the listener. It refers to the myItem that created when convertView was null. What if I remove that item from the list (the position changes)? Or if I add some items in front of it? Will my code fail with "null exception"? Or perform incorrectly? How I should build it?