首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 彈出式選單/下拉選單實作:PopupWindow、Spinner 與 Material Design 選單

     編輯:程式設計綜合問答

需求分析

圖示為點擊輸入框/按鈕後彈出選項列表,屬於典型下拉選單/彈出選單 UI 模式。

方案一:PopupWindow (最靈活、完全自訂)

// 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 (原生下拉框、最省碼)

<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) {}
});

方案三:Material Design Exposed Dropdown Menu (現代風格)

<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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved