第1步:将 setAdapter设置为列表视图。
listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, GENRES));
第2步:设置列表视图的选择模式。以下代码的第二行表示应选中哪个复选框。
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemChecked(2, true);
listView.setOnItemClickListener(this);
private static String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
第3步:在SparseBooleanArray中返回检查后的视图,因此您可以使用以下代码获取键或值。以下示例仅在单个String中显示所选名称。
@Override
public void onItemClick(AdapterView> adapter, View arg1, int arg2, long arg3)
{
SparseBooleanArray sp=getListView().getCheckedItemPositions();
String str="";
for(int i=0;i
{
str+=GENRES[sp.keyAt(i)]+",";
}
Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();
}