0

I hope to use lv.getCheckedItemIds().length to get the sum of selected items. It seems that ArrayAdapter doesn't support getCheckedItemIds(), right?

private void InitListView(int pos) {
    List<String> msgList = getSMS(pos);
    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, msgList);
    lv.setAdapter(adapter2);
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            SetSelectedAndTotal();
        }
    });
}

private void SetSelectedAndTotal(){
    selectedAndTotal.setText(lv.getCheckedItemIds().length+ "/"
            + lv.getCount());       
}


    public List<String> getSMS(int pos) {
        List<String> sms = new ArrayList<String>();
        Uri uriSMSURI = Uri.parse(valueList.get(pos));
        Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,
                null);

        while (cur.moveToNext()) {
            String address = cur.getString(cur.getColumnIndex("address"));
            String body = cur.getString(cur.getColumnIndexOrThrow("body"));
            sms.add("Number: " + address + " .Message: " + body);

        }
        return sms;
    }
4

1 回答 1

4

以下是使用文档中的片段getCheckedItemIds()

结果仅在未设置为choice_mode_none的选择模式并且适配器具有稳定的ID时才有效。(hasStableIds() == true)

默认情况下,BaseAdapter(及其子类ArrayAdapter)不支持稳定的项目 ID,因此如果您想利用它,您需要创建自己的子类,该子类从每个元素返回true并始终hasStableIds()返回一个唯一值。getItemId()

否则,您将不得不使用getCheckedItemPositions()它,在您描述的用例中,它将提供您需要的相同答案,而无需额外的工作。

于 2013-05-20T03:44:00.373 回答