1. listview有个属性
android:choiceMode ="singleChoice" 表示选择一个
android:choiceMode ="multipleChoice"表示选择两个
2. 布局中如下
<Button
android:id="@+id/button"
android:layout_width= "match_parent"
android:layout_height= "wrap_content"
android:text= "点击显示获取数字"
android:padding="10dp" />
<ListView
android:id="@+id/listView"
android:layout_below= "@+id/button"
android:layout_width= "match_parent"
android:layout_height= "match_parent"
android:choiceMode="singleChoice" >
</ListView>
3. java代码中为listview设置adapter,这里用默认的
private String[] GENRES = { "11", "22" , "33" , "44" , "55" , "66" , "77", "88" , "99" , "00" };
listView.setAdapter( new ArrayAdapter<String>( this,
android.R.layout.simple_list_item_single_choice , GENRES ));
simple_list_item_single_choice里的控件是
CheckedTextView,其实是一个实现了checkable接口的textView
4. 此时listView就有单选效果了,截图如下:
5. 如何获取已经选中的数据呢?这里单选或多选的数据会被控件记住,当我们点击显示获取数字的按钮时,我们用代码获取选中的信息,并显示
int position = listView .getCheckedItemPosition(); // 即获取选中位置
if(ListView.INVALID_POSITION != position){
Toast.makeText(MainActivity.this, groups.get(position), 0).show();
}
6. 附件源码