开发者

Checkboxes in ListActivity seem to be linked; why? How do I fix it?

开发者 https://www.devze.com 2023-03-16 05:14 出处:网络
I have an activity which inherits ListActivity, and shows a list populate via an XML layout and a custom adapter class. It all renders fine, and as expected. The row XML includes in it a checkbox.

I have an activity which inherits ListActivity, and shows a list populate via an XML layout and a custom adapter class. It all renders fine, and as expected. The row XML includes in it a checkbox.

Now, what's weird is that the checkboxes seem to be linked every so many rows. That is, if I check the checkbox in row 0, then it also checks the checkboxes in rows 8, 18, 28, 38, 48, etc.

Why would this be, and how can I fix it?

If it is pertinent, i am reusing the view passed into my adapter when it is available. It does also seem that when I scroll one of the checked ones to the top of the screen, the next one to be checked is the second one off the bottom of the screen.

Below is my getView code:

public开发者_StackOverflow中文版 View getView(int position, View convertView, ViewGroup parent) {     
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)
            mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.contacts_row, null);
    }

    cb.GroupMembership.moveToPosition(position);
    long cid = cb.GroupMembership.getLong(0);
    String clk = cb.GroupMembership.getString(1);
    String cnm = cb.GroupMembership.getString(2);
    long pid = cb.GroupMembership.getLong(3);

    ImageView bdg = (ImageView) v.findViewById(R.id.contactBadge);
    Uri pic = GroupsLib.getContactPhotoUri(pid);
    if (pic == null) {
        bdg.setImageResource(R.drawable.contactg);
    } else {
        bdg.setImageURI(pic);
    }

    ((TextView) v.findViewById(R.id.contactName)).setText(cnm);

    return v;
}


When you reuse your view you should actually set the state of all controls in it (so basically clean-up). Precisely because it is reused.

Usually it would look like (in adapter):

public View getView (int position, View convertView, ViewGroup parent) {
    SomeObject obj = getDataFromYourModel(position);
    if (convertView == null) { 
        convertView = ....; //inflate view here
    } 

    setMyViewParameters(obj,convertView);
}

public void setMyViewParameters(SomeObject obj, View view) {
    CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox_id);

    cb.setChecked(obj.isChecked);
    //other initialisation
}

This way, you always reset the values when the view is reused.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号