Android學習手冊-Spinner

Andreea
Feb 19, 2022

--

Spinner 下拉式選單

  1. 在strings.xml中建立字串陣列,再將此字串陣列設定給spinner元件成為選單
<resources>
<string name="app_name">spinner</string>
<string-array name="gender_list">
<item>男生</item>
<item>女生</item>
</string-array>
</resources>

2. 在介面布局檔(activity_main.xml)中加入spinner元件,並設定好屬性

<Spinner
android:id="@+id/spnGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:entries="@array/gender_list" />

3. MainActivity.java中取得spiinner元件,並設定處理程序

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Spinner mspnGender = findViewById(R.id.spnGender);
mspnGender.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//選擇選項要做的事
switch (position){
case 0:
mGender = "男生";
break;
case 1:
mGender = "";
break;
}
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
//沒有選擇選項要做的事
}
});

--

--