ListFragment with multiple choice

It is a example to implement ListFragment with multiple choice.

ListFragment with multiple choice

Base on my old exercise of "ListFragment".

Modify MyListFragment1.java, create ListAdapter with android.R.layout.simple_list_item_multiple_choice. Also modify onListItemClick() to display the clicked item and selected items.
package com.exercise.AndroidListFragment;

import android.app.ListFragment;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MyListFragment1 extends ListFragment {

String[] month ={
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

ListAdapter myListAdapter = new ArrayAdapter<String>(
getActivity(),
android.R.layout.simple_list_item_multiple_choice,
month);

setListAdapter(myListAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.listfragment1, container, false);

}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

String prompt =
"clicked item: " + getListView().getItemAtPosition(position).toString() + "\n\n";

prompt += "selected items: \n";
int count = getListView().getCount();
SparseBooleanArray sparseBooleanArray = getListView().getCheckedItemPositions();
for (int i = 0; i < count; i++){
if (sparseBooleanArray.get(i)) {
prompt += getListView().getItemAtPosition(i).toString() + "\n";
}
}

Toast.makeText(
getActivity(),
prompt,
Toast.LENGTH_LONG).show();
}

}

Modify listfragment1.xml to add android:choiceMode="multipleChoice" in <ListView>.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp" >

<ListView
android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:choiceMode="multipleChoice"
android:drawSelectorOnTop="false" />

<TextView
android:id="@id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="No data" />

</LinearLayout>


download filesDownload the files.