在Android 中 Material design 中有一個特別的Spinner。甚至可以仿ios 的設計,讓選項由螢幕下面出現
長的大概會像這樣
現在來參一下他的用法吧
首先在build.gradle 中加上
allprojects {
repositories {
google()
jcenter()
maven { url "https://jitpack.io" }}
}
接著在module中加入
implementation 'com.github.tiper:MaterialSpinner:1.4.1'
在layout 中設計加入MaterialSpinner物件,以呈現下拉選項功能
<com.tiper.MaterialSpinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:spinnerMode="bottomsheet"
/>
其中app:spinnerMode="bottomsheet"
為控制選單的結果由螢幕下方彈出
完整layout 寫法為
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"xmlns:app="http://schemas.android.com/apk/res-auto"tools:context=".Fragments.MedicationStyleFragment"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><com.google.android.material.textfield.TextInputLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:hint="藥名"><com.google.android.material.textfield.TextInputEditTextandroid:id="@+id/medical_name"android:layout_height="wrap_content"android:layout_width="match_parent"/></com.google.android.material.textfield.TextInputLayout><com.tiper.MaterialSpinnerandroid:id="@+id/dose_spinner"android:layout_width="match_parent"android:layout_height="wrap_content"app:spinnerMode="bottomsheet"app:helperTextEnabled="true"android:hint="劑量"/><com.tiper.MaterialSpinnerandroid:id="@+id/style_spinner"android:layout_width="match_parent"android:layout_height="wrap_content"app:spinnerMode="bottomsheet"android:hint="用藥方式"/></LinearLayout></FrameLayout>
在Java 中 com.tiper.MaterialSpinner
為一MaterialSpinner 物件,因此在程式中必須先宣告為 MaterialSpinner dose_spinner,style_spinner
物件,其性質與spinner相近,可用setAdapter 方法加入選單的內容
可參考下列的寫法
MaterialSpinner dose_spinner,style_spinner;
ArrayAdapter dose_adapte,style_adpater;public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {View v = inflater.inflate(R.layout.fragment_medication_style, container, false);
dose_spinner = v.findViewById(R.id.dose_spinner);
style_spinner= v.findViewById(R.id.style_spinner); dose_adapter = new ArrayAdapter<>(getContext()
,android.R.layout.simple_dropdown_item_1line
,new String[]{"半顆","一顆"}); dose_spinner.setAdapter(dose_adapter); style_adpater= new ArrayAdapter<>(getContext()
,android.R.layout.simple_dropdown_item_1line
,new String[]{"每天早上","睡前","三餐飯前","三餐飯後"});
style_adapter.setAdapter(style_adpater); return v;}