在Android中的ListView选单组件,是以下列表方式来列出选项,供用户选择。
ListView组件属性设置:
创建spinner组件时,只需要设置一项entries属性即可使用。此属性是设置要放在列表中的文字内容,不可以像text View的text属性那样直接指定字符串,是必须先在value/string.xml中创建字符串数组,再将数组名指定给entri属性,当程序执行时就会列出数组内容。举个简单的例子:
string.xml数组如下
1 <string-array name="habit"> 2 <item>晨跑</item> 3 <item>健身</item> 4 <item>爬山</item> 5 <item>游泳</item> 6 <item>篮球</item> 7 <item>足球</item> 8 </string-array>
布局文件代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:orientation="vertical" 8 tools:context="com.hs.example.exampleapplication.ListViewActivity"> 9 10 <TextView 11 android:id="@+id/select" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:gravity="center" 15 android:textSize="25sp" 16 android:text="请选择你喜欢的运动!"/> 17 18 <ListView 19 android:id="@+id/lv_sele" 20 android:layout_width="match_parent" 21 android:layout_height="wrap_content" 22 android:entries="@array/habit"> 23 24 </ListView> 25 26 </LinearLayout>
逻辑处理代码如下:
1 public class ListViewActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{ 2 3 ListView listV ; 4 ArrayList<String> selected = new ArrayList<>(); 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_listview); 10 11 listV = this.findViewById(R.id.lv_sele); 12 listV.setOnItemClickListener(this); 13 } 14 15 @Override 16 public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 17 TextView textView = (TextView) view; //被点击的view对象转换成textView对象 18 String item = textView.getText().toString();//获取选中的文字 19 if(selected.contains(item)){ //如果集合中已经有该选项,再次点击则删除 20 selected.remove(item); 21 }else{ //否则就添加进去 22 selected.add(item); 23 } 24 String msg ; 25 if(selected.size()>0){ 26 msg = "你喜欢的运动有:"; 27 for(String str : selected){ //遍历数组中的选项,转换成字符串添加到msg中 28 msg += str.toString() + " | "; 29 } 30 }else{ 31 msg = "请选择你喜欢的运动!"; 32 } 33 TextView msgText = this.findViewById(R.id.select); 34 msgText.setText(msg); 35 } 36 }
运行效果如下图: