圖示為點擊輸入框/按鈕後彈出選項列表,屬於典型下拉選單/彈出選單 UI 模式。
// 1. 佈局檔 res/layout/popup_menu.xml
<ListView xmlns:android="..."
android:id="@+id/lvOptions"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />
// 2. Activity/Fragment 中
ListView listView = (ListView) LayoutInflater.from(context)
.inflate(R.layout.popup_menu, null);
listView.setAdapter(new ArrayAdapter<>(context,
android.R.layout.simple_list_item_1, options));
PopupWindow popup = new PopupWindow(listView,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popup.setOutsideTouchable(true);
popup.showAsDropDown(anchorView, xOffset, yOffset);
// 3. 項目點擊
listView.setOnItemClickListener((parent, view, position, id) -> {
String selected = options[position];
// 回填輸入框、關閉彈窗
editText.setText(selected);
popup.dismiss();
});
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/city_list" />
// Java
Spinner spinner = findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override public void onItemSelected(AdapterView> parent, View view, int pos, long id) {
String val = parent.getItemAtPosition(pos).toString();
}
@Override public void onNothingSelected(AdapterView> parent) {}
});
<com.google.android.material.textfield.TextInputLayout
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/autoComplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none" />
</com.google.android.material.textfield.TextInputLayout>
// Java
AutoCompleteTextView actv = findViewById(R.id.autoComplete);
actv.setAdapter(new ArrayAdapter<>(this,
R.layout.dropdown_menu_popup_item, options));
actv.setOnItemClickListener((parent, view, pos, id) -> {
String selected = options[pos];
});
| 場景 | 推薦方案 |
|---|---|
| 簡單單選、表單欄位 | Spinner / Exposed Dropdown Menu |
| 複雜佈局、多欄位、動畫、錨點定位 | PopupWindow / BottomSheetDialogFragment |
| 動作表單 | BottomSheetDialogFragment |