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
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()));
}