带有光标适配器滚动问题的android列表视图

时间:2012-05-17 13:20:13

标签: android listview scroll android-listview android-contacts

在我的应用中,我在列表视图中加载了联系人。我有listview图像,文本和复选框,并由游标适配器实现。我的问题是当我向上/向下滚动列表视图时,它的位置发生了变化。也就是说,如果选择(勾选复选框)位置1,3,4,2并向下和向上滚动,则勾选的位置会随机更改。我花了更多的时间来找到解决方案,但我无法得到它。请帮帮我。

我的代码ex for adapter:

    public class ContactsListAdapter extends CursorAdapter {

    ContentResolver cr;
    private final LayoutInflater mInflater;
    private Context mContext;

    @SuppressWarnings("unchecked")
    public ContactsListAdapter(Context context, Cursor c,ArrayList<ContactPhoneInfo> selected) {
        super(context, c, true);
        this.checkedContacts = (ArrayList<ContactPhoneInfo>) selected.clone();
        mInflater = LayoutInflater.from(context);
        this.mContext = context;
    }

    public void bindView(View view,Context context_bind, Cursor cursor)
    {   
        final LinearLayout linear = (LinearLayout) view.findViewById(R.id.contacts_linearLayout1);
        final TextView contactEntryText = (TextView) view.findViewById(R.id.contacts_txtViewContactName);
        final CheckBox chkContact = (CheckBox) view.findViewById(R.id.contacts_chkContact);
        final TextView textCaption = (TextView) view.findViewById(R.id.contacts_layoutCaption);
        final ImageView photoView = (ImageView)view.findViewById(R.id.contacts_imgViewcontact);

        ContentResolver cr = context_bind.getContentResolver();
            .......

        int id = Integer.parseInt(cursor.getString(0));
        final String name = cursor.getString(1);

        contactEntryText.setText(name);
            .......
        view.setClickable(true);
        view.setFocusable(true);

        view.setOnClickListener(new OnClickListener() {
            public void onClick(View v) 
            {
                chkContact.setChecked(!chkContact.isChecked());
            }
        });

        chkContact.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                .buttonView.........
            }
        });
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View view = mInflater.inflate(R.layout.contacts_listitem, parent,
                false);
        return view;
    }
}

调用类编码:

        contactsListAdapter = new ContactsListAdapter(this,app.loadContactCursor(""),checkedContacts);
    setListAdapter(contactsListAdapter);

1 个答案:

答案 0 :(得分:1)

我通过调用 setOnCheckedChangeListener 方法解决了我的问题,然后再调用 setChecked

    chkContact.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            .buttonView.........
        }
    });

之后

chkContact.setChecked(!chkContact.isChecked());

我在流程问题上引用以下堆栈:

Android listview with checkbox problem