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

Shr*_*Rao 5 checkbox android listview android-layout android-listview

我试图读取多个列表中的联系人checkboxes,但是当我调用sparsebooleanarray..对于所有列表条目只返回false时,即使对于那个已检查的...我查看了这个帖子为什么是ListView. getCheckedItemPositions()没有返回正确的值?...但是当我实现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);

                }


            }
        }



    });                 
}
Run Code Online (Sandbox Code Playgroud)

Sit*_*ten 1

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

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

喜欢...

holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

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

            }
        });         
Run Code Online (Sandbox Code Playgroud)

现在看整个例子:

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 ;
    }       
}
Run Code Online (Sandbox Code Playgroud)

试试这个——它将帮助您获得位置以及检查是否正确。