ListView.getCheckedItemPositions无法返回SparseBooleanArray中的已检查项

时间:2011-06-15 04:25:40

标签: android listview checkbox android-layout android-listview

我正在尝试使用多个checkboxes读取列表中的联系人,但是当我调用sparsebooleanarray时,它只会为所有列表条目返回false,即使是一个检查...我查看了这个帖子Why is ListView.getCheckedItemPositions() not returning correct values? ...但是当我实现addClickHandlerToCheckBox时,它会停止..这已经困扰了我4天..请任何帮助..

 public void populateContactList() {
    // Build adapter with contact entries
    final Cursor cursor = getContacts();
    String[] fields = new String[] {
            ContactsContract.Data.DISPLAY_NAME
    };

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry, cursor,
            fields, new int[] {R.id.contactEntryText});
    mContactList.setAdapter(adapter);
    mContactList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);



    proceedButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {


            SparseBooleanArray checked=mContactList.getCheckedItemPositions();

            int len = mContactList.getCount();


            for(int i=0;i<len;i++)
           {

                if(checked.get(i)==true)
                {

                    String item =  mContactList.getAdapter().getItem(checked.keyAt(i)).toString();
                    edt.append(","+item);

                }


            }
        }



    });                 
}

1 个答案:

答案 0 :(得分:1)

我认为您应该使用列表适配器视图。

它将提供一个onCheckedChanged监听器,因此您也将获得该位置。

...一样

holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int cupos = position+1;

            }
        });         

现在看一下整个例子:

Listview.setAdapter(new settingsBase(getApplicationContext()));

private class settingsBase extends BaseAdapter{

    public settingsBase(Context context) {
       layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return listview.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder ;
     holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int cupos = position+1;

            }
        });         


        return convertView;
    }

    class ViewHolder{
        TextView txtSettingname , txtShow ;
        RadioButton radioButton ;
    }       
}

试试这个 - 它会帮助你获得位置,无论是真还是假。