Android學習手冊-Spinner

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) {
//沒有選擇選項要做的事
}
});

--

--

IM rookie

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store