Android ListView with Checkboxes: How to capture checked items?

前端 未结 1 1347
一整个雨季
一整个雨季 2021-01-03 12:15

I have to do a ListView with CheckBoxes and then display the checked and unchecked items when user presses the button. The problem is I don\'t know

相关标签:
1条回答
  • 2021-01-03 12:55

    I didn't completely understand what the problem is but I can provide you one useful extension of ListView which helps you manipulate with string data (set\get checked values):

    public class MultipleChoiceListView extends ListView {
    
    public MultipleChoiceListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    
    public MultipleChoiceListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public MultipleChoiceListView(Context context) {
        super(context);
    }
    
    @Override
    public void setAdapter(ListAdapter adapter) {
        throw new RuntimeException(
            "This component doesn't support custom adapter. Use setData method to supply some data to show.");
    }
    
    /**
     * Sets the data that should be displayed for choosing
     * 
     * @param data List<String>
     */
    public void setData(List<String> data) {
        super.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_multiple_choice, data));
        super.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }
    
    /**
     * Sets the data that should be choosen by default
     * 
     * @param checkedData List<String>
     */
    public void setCheckedData(List<String> checkedData) {
        for (int index = 0; index < getCount(); index++) {
            if (checkedData.contains(getItemAtPosition(index))) {
                setItemChecked(index, true);
            }
        }
    }
    
    /**
     * Returns checked by the user data passed in {@link #setData(List)}
     * 
     * @return List<String>
     */
    public List<String> getCheckedData() {
        SparseBooleanArray checked = getCheckedItemPositions();
        List<String> checkedResult = new ArrayList<String>();
    
        for (int i = 0; i < checked.size(); i++) {
            if (checked.valueAt(i)) {
                checkedResult.add(getAdapter().getItem(checked.keyAt(i)).toString());
            }
        }
        return checkedResult;
    }
    

    }

    Example of using:

        private void initListMultiple() {
        String[] data = new String[] {"first", "second", "third", "forth"};
        String[] checkedData = new String[] {"second", "forth"};
    
        multipleChoiceListView.setData(Arrays.asList(data));
        multipleChoiceListView.setCheckedData(Arrays.asList(checkedData));
    }
    
    private void onTestListButtonClicked(View view) {
        listResultTextView.setText(Arrays.toString(listView.getCheckedData().toArray()));
    }
    
    0 讨论(0)
提交回复
热议问题