在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 }
運行效果如下圖: