Android 在listview中选中复选框以选择多个联系人

Android 在listview中选中复选框以选择多个联系人,android,listview,Android,Listview,我曾试图通过布局充气器将复选框放入listview,但我成功了,但问题是当我选择多个联系人时没有问题,但当我取消选择它时&当我向下滚动时&然后返回到取消选择的复选框时,它会自动被选中 public class Contactlist_selfActivity extends ListActivity { /** Called when the activity is first created. */ private ArrayList<contact> contact_list

我曾试图通过布局充气器将复选框放入listview,但我成功了,但问题是当我选择多个联系人时没有问题,但当我取消选择它时&当我向下滚动时&然后返回到取消选择的复选框时,它会自动被选中

public class Contactlist_selfActivity extends ListActivity {
/** Called when the activity is first created. */

private ArrayList<contact> contact_list = null;
private ProgressDialog mProgressDialog = null;
private contactAdapter mContactAdapter = null;
private Runnable mViewcontacts = null;
private SparseBooleanArray mSelectedContacts = new SparseBooleanArray();
private ArrayList<contact> items;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    contact_list = new ArrayList<contact>();
    this.mContactAdapter = new contactAdapter(this, R.layout.listview,
            contact_list);
    ListView lv = getListView();
    setListAdapter(this.mContactAdapter);
    lv.setItemsCanFocus(false);
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    // }
    mViewcontacts = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            getContacts();
        }
    };

    Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground");
    thread.start();
    mProgressDialog = ProgressDialog.show(Contactlist_selfActivity.this,
            "Please Wait...", "Retriving Contacts...", true);
}

@SuppressWarnings("unused")
private void getContacts() {
    // TODO Auto-generated method stub

    try {

        String[] projection = new String[] {
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.HAS_PHONE_NUMBER,
                ContactsContract.Contacts._ID };

        Cursor mCursor = managedQuery(
                ContactsContract.Contacts.CONTENT_URI, projection,
                ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?",
                new String[] { "1" },
                ContactsContract.Contacts.DISPLAY_NAME);

        while (mCursor.moveToNext()) {
            contact contact = new contact();

            String contactId = mCursor.getString(mCursor
                    .getColumnIndex(ContactsContract.Contacts._ID));

            contact.setContactName(mCursor.getString(mCursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
            contact_list.add(contact);
        }
        mCursor.close();

        runOnUiThread(returnRes);

    } catch (Exception e) {
        // TODO: handle exception
        Log.d("getContacts", e.getMessage());
    }
}

public class contactAdapter extends ArrayAdapter<contact> {
    private int[] isChecked;

    public contactAdapter(Context context, int textViewResourceId,
            ArrayList<contact> items1) {
        super(context, textViewResourceId, items1);
        items = items1;
    }

    @Override
    public View getView(final int position, View convertView,
            ViewGroup parent) {
        // TODO Auto-generated method stub
        final int position_clicked = 0;
        // Log.i("asd", "getView :" + getItem(position));

        if (convertView == null) {

            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.listview, parent, false);
        }

        contact contacts = items.get(position);
        isChecked = new int[items.size()];

        if (contacts != null) {
            final CheckBox nameCheckBox = (CheckBox) convertView
                    .findViewById(R.id.checkBox);
            nameCheckBox.setChecked(mSelectedContacts.get(position));

            for (int i = 0; i < isChecked.length; i++) {

            }

            if (nameCheckBox != null) {
                nameCheckBox.setText(contacts.getContactName());
            }

            nameCheckBox.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    isChecked[position_clicked] = position;
                    Log.d("position", String.valueOf(position));
                }
            });

        }

        return convertView;
    }
}

private Runnable returnRes = new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        if (mProgressDialog.isShowing())
            mProgressDialog.dismiss();
        mContactAdapter.notifyDataSetChanged();
    }
};
}
public class Contactlist\u selfActivity扩展了ListActivity{
/**在首次创建活动时调用*/
private ArrayList contact_list=null;
private ProgressDialog mProgressDialog=null;
私有contactAdapter mContactAdapter=null;
私有可运行mViewcontacts=null;
专用SparseBooleanArray mSelectedContacts=新SparseBooleanArray();
私有ArrayList项;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
联系人列表=新建ArrayList();
this.mContactAdapter=新的contactAdapter(this,R.layout.listview,
联系人名单);
ListView lv=getListView();
setListAdapter(this.mContactAdapter);
lv.setItemsCanFocus(假);
lv.setChoiceMode(ListView.CHOICE\u MODE\u MULTIPLE);
// }
mViewcontacts=newrunnable(){
@凌驾
公开募捐{
//TODO自动生成的方法存根
getContacts();
}
};
线程线程=新线程(null,mViewcontacts,“ContactReadBackground”);
thread.start();
mProgressDialog=ProgressDialog.show(Contactlist\u selfActivity.this,
“请稍候…”,“正在检索联系人…”,正确);
}
@抑制警告(“未使用”)
私有联系人(){
//TODO自动生成的方法存根
试一试{
字符串[]投影=新字符串[]{
Contacts contract.Contacts.DISPLAY\u NAME,
Contacts contract.Contacts.HAS_电话号码,
Contacts contract.Contacts.\u ID};
游标mCursor=managedQuery(
Contacts contract.Contacts.CONTENT\u URI,投影,
Contacts contract.Contacts.HAS_PHONE_NUMBER+“=?”,
新字符串[]{“1”},
联系人contract.Contacts.DISPLAY\u NAME);
while(mCursor.moveToNext()){
触点=新触点();
String contactId=mCursor.getString(mCursor
.getColumnIndex(Contacts contract.Contacts._ID));
contact.setContactName(mCursor.getString(mCursor
.getColumnIndex(Contacts.Contacts.DISPLAY_NAME));
联系人列表。添加(联系人);
}
mCursor.close();
runOnUiThread(returnRes);
}捕获(例外e){
//TODO:处理异常
Log.d(“getContacts”,例如getMessage());
}
}
公共类contactAdapter扩展了ArrayAdapter{
检查私有int[]的值;
公共contactAdapter(上下文,int textViewResourceId,
ArrayList项目1){
super(上下文,textViewResourceId,items1);
项目=项目1;
}
@凌驾
公共视图getView(最终整型位置,视图转换视图,
视图组(父级){
//TODO自动生成的方法存根
最终整数位置=0;
//Log.i(“asd”、“getView:+getItem(位置));
if(convertView==null){
LayoutInflater vi=(LayoutInflater)getSystemService(Context.LAYOUT\u INFLATER\u SERVICE);
convertView=vi.充气(R.layout.listview,父项,false);
}
联系人=项目。获取(位置);
isChecked=newint[items.size()];
如果(联系人!=null){
最终复选框名称复选框=(复选框)convertView
.findViewById(R.id.checkBox);
nameCheckBox.setChecked(mSelectedContacts.get(position));
for(int i=0;i
这是因为在code
OnClickListener()
中调用
nameCheckBox.setChecked()
时会唤醒并运行其代码。我在设置复选框是否选中之前设置了
OnClickListener(null)
,解决了同样的问题。

这是因为当您在code
OnClickListener()
中调用
nameCheckBox.setChecked()
时,会唤醒并运行其代码。在设置复选框是否选中之前,我只需设置
OnClickListener(null)
,就解决了同样的问题。

nameCheckBox.setOnClickListener(new OnClickListener()){

此代码在“添加多个欠款”列表中存储所有位置并添加或删除这两个表示 快速添加,第二次删除。
并用于在适当位置列出其他方法

nameCheckBox.setOnClickListener(新的OnClickListener(){

此代码在“添加多个欠款”列表中存储所有位置并添加或删除这两个表示 快速添加,第二次删除。 并用来列出你的其他方法

我找到了答案。。。。 我刚在contact类中使用了一个新变量

public class PlanetsActivity extends Activity {
private ListView mainListView;
private Contact[] contact_read;
private Cursor mCursor;
private ArrayAdapter<Contact> listAdapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Find the ListView resource.
    mainListView = (ListView) findViewById(R.id.mainListView);

    mainListView
            .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View item,
                        int position, long id) {
                    Contact planet = listAdapter.getItem(position);
                    planet.toggleChecked();
                    ContactViewHolder viewHolder = (ContactViewHolder) item
                            .getTag();
                    viewHolder.getCheckBox().setChecked(planet.isChecked());
                }
            });

    // Throw Query and fetch the contacts.

    String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER,
            Contacts._ID, Contacts.DISPLAY_NAME };

    mCursor = managedQuery(Contacts.CONTENT_URI, projection,
            Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
            Contacts.DISPLAY_NAME);

    if (mCursor != null) {
        mCursor.moveToFirst();
        contact_read = new Contact[mCursor.getCount()];

        // Add Contacts to the Array

        int j = 0;
        do {

            contact_read[j] = new Contact(mCursor.getString(mCursor
                    .getColumnIndex(Contacts.DISPLAY_NAME)));
            j++;
        } while (mCursor.moveToNext());

    } else {
        System.out.println("Cursor is NULL");
    }

    // Add Contact Class to the Arraylist

    ArrayList<Contact> planetList = new ArrayList<Contact>();
    planetList.addAll(Arrays.asList(contact_read));

    // Set our custom array adapter as the ListView's adapter.
    listAdapter = new ContactArrayAdapter(this, planetList);
    mainListView.setAdapter(listAdapter);
}

/** Holds Contact data. */
@SuppressWarnings("unused")
private static class Contact {
    private String name = "";
    private boolean checked = false;

    public Contact() {
    }

    public Contact(String name) {
        this.name = name;
    }

    public Contact(String name, boolean checked) {
        this.name = name;
        this.checked = checked;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public String toString() {
        return name;
    }

    public void toggleChecked() {
        checked = !checked;
    }
}

/** Holds child views for one row. */
@SuppressWarnings("unused")
private static class ContactViewHolder {
    private CheckBox checkBox;
    private TextView textView;

    public ContactViewHolder() {
    }

    public ContactViewHolder(TextView textView, CheckBox checkBox) {
        this.checkBox = checkBox;
        this.textView = textView;
    }

    public CheckBox getCheckBox() {
        return checkBox;
    }

    public void setCheckBox(CheckBox checkBox) {
        this.checkBox = checkBox;
    }

    public TextView getTextView() {
        return textView;
    }

    public void setTextView(TextView textView) {
        this.textView = textView;
    }
}

/** Custom adapter for displaying an array of Contact objects. */
private static class ContactArrayAdapter extends ArrayAdapter<Contact> {

    private LayoutInflater inflater;

    public ContactArrayAdapter(Context context, List<Contact> planetList) {
        super(context, R.layout.simplerow, R.id.rowTextView, planetList);
        // Cache the LayoutInflate to avoid asking for a new one each time.
        inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Contact to display
        Contact planet = (Contact) this.getItem(position);
        System.out.println(String.valueOf(position));

        // The child views in each row.
        CheckBox checkBox;
        TextView textView;

        // Create a new row view
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.simplerow, null);

            // Find the child views.
            textView = (TextView) convertView
                    .findViewById(R.id.rowTextView);
            checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);

            // Optimization: Tag the row with it's child views, so we don't
            // have to
            // call findViewById() later when we reuse the row.
            convertView.setTag(new ContactViewHolder(textView, checkBox));

            // If CheckBox is toggled, update the Contact it is tagged with.
            checkBox.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    Contact contact = (Contact) cb.getTag();
                    contact.setChecked(cb.isChecked());
                }
            });
        }
        // Reuse existing row view
        else {
            // Because we use a ViewHolder, we avoid having to call
            // findViewById().
            ContactViewHolder viewHolder = (ContactViewHolder) convertView
                    .getTag();
            checkBox = viewHolder.getCheckBox();
            textView = viewHolder.getTextView();
        }

        // Tag the CheckBox with the Contact it is displaying, so that we
        // can
        // access the Contact in onClick() when the CheckBox is toggled.
        checkBox.setTag(planet);

        // Display Contact data
        checkBox.setChecked(planet.isChecked());
        textView.setText(planet.getName());

        return convertView;
    }

}

public Object onRetainNonConfigurationInstance() {
    return contact_read;
}
公共类平面活动扩展活动{
私有ListView主ListView;
私人联系人[]联系人_read;
私有游标mCursor;
专用阵列适配器列表适配器;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState)
public class PlanetsActivity extends Activity {
private ListView mainListView;
private Contact[] contact_read;
private Cursor mCursor;
private ArrayAdapter<Contact> listAdapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Find the ListView resource.
    mainListView = (ListView) findViewById(R.id.mainListView);

    mainListView
            .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View item,
                        int position, long id) {
                    Contact planet = listAdapter.getItem(position);
                    planet.toggleChecked();
                    ContactViewHolder viewHolder = (ContactViewHolder) item
                            .getTag();
                    viewHolder.getCheckBox().setChecked(planet.isChecked());
                }
            });

    // Throw Query and fetch the contacts.

    String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER,
            Contacts._ID, Contacts.DISPLAY_NAME };

    mCursor = managedQuery(Contacts.CONTENT_URI, projection,
            Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
            Contacts.DISPLAY_NAME);

    if (mCursor != null) {
        mCursor.moveToFirst();
        contact_read = new Contact[mCursor.getCount()];

        // Add Contacts to the Array

        int j = 0;
        do {

            contact_read[j] = new Contact(mCursor.getString(mCursor
                    .getColumnIndex(Contacts.DISPLAY_NAME)));
            j++;
        } while (mCursor.moveToNext());

    } else {
        System.out.println("Cursor is NULL");
    }

    // Add Contact Class to the Arraylist

    ArrayList<Contact> planetList = new ArrayList<Contact>();
    planetList.addAll(Arrays.asList(contact_read));

    // Set our custom array adapter as the ListView's adapter.
    listAdapter = new ContactArrayAdapter(this, planetList);
    mainListView.setAdapter(listAdapter);
}

/** Holds Contact data. */
@SuppressWarnings("unused")
private static class Contact {
    private String name = "";
    private boolean checked = false;

    public Contact() {
    }

    public Contact(String name) {
        this.name = name;
    }

    public Contact(String name, boolean checked) {
        this.name = name;
        this.checked = checked;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public String toString() {
        return name;
    }

    public void toggleChecked() {
        checked = !checked;
    }
}

/** Holds child views for one row. */
@SuppressWarnings("unused")
private static class ContactViewHolder {
    private CheckBox checkBox;
    private TextView textView;

    public ContactViewHolder() {
    }

    public ContactViewHolder(TextView textView, CheckBox checkBox) {
        this.checkBox = checkBox;
        this.textView = textView;
    }

    public CheckBox getCheckBox() {
        return checkBox;
    }

    public void setCheckBox(CheckBox checkBox) {
        this.checkBox = checkBox;
    }

    public TextView getTextView() {
        return textView;
    }

    public void setTextView(TextView textView) {
        this.textView = textView;
    }
}

/** Custom adapter for displaying an array of Contact objects. */
private static class ContactArrayAdapter extends ArrayAdapter<Contact> {

    private LayoutInflater inflater;

    public ContactArrayAdapter(Context context, List<Contact> planetList) {
        super(context, R.layout.simplerow, R.id.rowTextView, planetList);
        // Cache the LayoutInflate to avoid asking for a new one each time.
        inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Contact to display
        Contact planet = (Contact) this.getItem(position);
        System.out.println(String.valueOf(position));

        // The child views in each row.
        CheckBox checkBox;
        TextView textView;

        // Create a new row view
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.simplerow, null);

            // Find the child views.
            textView = (TextView) convertView
                    .findViewById(R.id.rowTextView);
            checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);

            // Optimization: Tag the row with it's child views, so we don't
            // have to
            // call findViewById() later when we reuse the row.
            convertView.setTag(new ContactViewHolder(textView, checkBox));

            // If CheckBox is toggled, update the Contact it is tagged with.
            checkBox.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    Contact contact = (Contact) cb.getTag();
                    contact.setChecked(cb.isChecked());
                }
            });
        }
        // Reuse existing row view
        else {
            // Because we use a ViewHolder, we avoid having to call
            // findViewById().
            ContactViewHolder viewHolder = (ContactViewHolder) convertView
                    .getTag();
            checkBox = viewHolder.getCheckBox();
            textView = viewHolder.getTextView();
        }

        // Tag the CheckBox with the Contact it is displaying, so that we
        // can
        // access the Contact in onClick() when the CheckBox is toggled.
        checkBox.setTag(planet);

        // Display Contact data
        checkBox.setChecked(planet.isChecked());
        textView.setText(planet.getName());

        return convertView;
    }

}

public Object onRetainNonConfigurationInstance() {
    return contact_read;
}