Spinner是一個Android Studio內建的一個下拉式選單功能元件,最常見是在網購選擇數量的時候會用到這個功能,下方先放上成果影像。
在XML畫面上新增一個元件Spinner
<Spinner
android:id="@+id/quantityspinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/productname"
tools:ignore="MissingConstraints" />
<string-array name="quantity">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
<item>8</item>
<item>9</item>
<item>10</item>
<item>11</item>
<item>12</item>
<item>13</item>
</string-array>
quantity = new String[] { "請選擇數量", "1", "2", "3","4","5","6","7","8","9","10","11" };
quantityspinner = findViewById (R.id.quantityspinner);
quantityspinner = (Spinner)findViewById(R.id.quantityspinner);
ArrayAdapter<CharSequence> adapter;
adapter = ArrayAdapter.createFromResource(this,
R.array.quantity,
android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
quantityspinner.setAdapter(adapter);
//Spinner創建
quantityspinner = findViewById (R.id.quantityspinner);
quantity = new String[] { "請選擇數量", "1", "2", "3","4","5","6","7","8","9","10","11" };
quantityspinner = (Spinner)findViewById(R.id.quantityspinner);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<> (this, android.R.layout.simple_spinner_dropdown_item,
quantity);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
quantityspinner.setAdapter(adapter);