Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 PopupWindow 做出 ListView 風格的自訂選單

Android 4.0 之後,系統原生選單的樣式越來越少被採用,取而代之的是自成一格的彈出式列表。要達到那種效果,關鍵是「攔下系統選單,改顯示自己的視圖」。

步驟一:先讓系統選單有東西可攔

必須先建立至少一個選項,否則 onMenuOpened 根本不會被觸發:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add("menu");   // 必須建立一項
    return super.onCreateOptionsMenu(menu);
}

步驟二:在 onMenuOpened 中換成自己的視圖

@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    switchSysMenuShow();
    return false;   // 必須回傳 false,傳 true 系統 menu 還是會跳出來
}

回傳值是最容易忽略的一環:傳 true 代表「我處理好了,請顯示系統 menu」,於是兩層選單會疊在一起。這一行的意義就是「我接手了,但不要顯示原生 UI」。

步驟三:按 ListView 規格配置布局

彈出的是一個列表,因此布局要以 ListView 為主體:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:paddingLeft="20dip"
    android:gravity="right"
    android:id="@+id/hotalk_menu_view_layout">

    <!-- 顯示的 listview -->
    <ListView
        android:id="@+id/hotalk_menu_listview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="7.6dip"
        android:paddingRight="7.6dip"
        android:fadingEdge="none"
        android:focusable="true"
        android:longClickable="true"
        android:scrollbarSize="0sp"
        android:scrollbarStyle="insideOverlay"
        android:background="@drawable/menu_bg_popup"
        android:divider="@drawable/menu_bg_line"
        android:dividerHeight="1px"
        android:cacheColorHint="#00000000" />
</RelativeLayout>

幾個屬性的用意

  • fadingEdge="none":去掉列表上下緣的漸層陰影,讓彈出菜單邊緣乾淨。
  • scrollbarSize="0sp":選單項目通常不多,隱藏 scrollbar 更清爽。
  • cacheColorHint="#00000000":關掉 ListView 預設的不透明快取色,避免背景在滾動時整片變色,這是自訂背景時的必要設定。
  • divider 與 dividerHeight:用自繪的細線取代系統分隔線,視覺上更貼近設計稿。

接著要做的事

剩下就是替 ListView 準備 Adapter、在 switchSysMenuShow() 裡把這個布局 inflate 成 PopupWindow 並 showAtLocation 定位,以及處理項目點擊後關閉視圖。整體思路是「借用系統選單的時機,換上自己的 UI」,如此既保有原生按鍵的觸發行為,又能完全掌控外觀。

Copyright © Linux教程網 All Rights Reserved