【Android】ListPopupWindow

#ListPopupWindowandroid

##ListPopupWindow簡述git

ListPopupWindow最低要求爲api11,爲了兼容到2.1, 能夠使用包含在support V7包中實現。 從效果上來說,ListPopupWindow就是一個彈出層的ListView,比較適合用來實現自定義的下拉菜單以及自定義的下拉選擇列表。api

##ListPopupWindow的使用微信

###自定義樣式ide

一個示例:this

<style name="V7.ListPopupWindowStyle" parent="@style/Widget.AppCompat.ListPopupWindow">
    <item name="android:popupBackground">#404040</item> //彈出層的背景
    <item name="android:dropDownVerticalOffset">0dip</item>
    <item name="android:dropDownHorizontalOffset">0dip</item> //水平以及垂直位移
    <item name="android:dropDownWidth">match_parent</item> //這個效果不大
</style>

<style name="V7.DropDownListViewStyle" parent="@style/Widget.AppCompat.ListView.DropDown">
    <item name="android:listSelector">@drawable/list_selector</item> //
    <item name="android:divider">#242424</item>
    <item name="android:dividerHeight">1px</item>

    ... //其餘列表樣式
tyle>

AppTheme是應用到Activity的主題
listPopupWindowStyle 對應彈出層的主題樣式
dropDownListViewStyle 對應內含列表的主題樣式,與普通ListView的定製方式一致

<style name="V7.ListPopupWindow" parent="AppTheme">
    <item name="listPopupWindowStyle">@style/V7.ListPopupWindowStyle</item>
    <item name="dropDownListViewStyle">@style/V7.DropDownListViewStyle</item>
</style>

###代碼調用.net

實現微信右上角彈出菜單,使用方式與PopupWindow差很少:code

ListPopupWindow listPopupWindow = new ListPopupWindow(this);
listPopupWindow.setAnchorView(view);
listPopupWindow.setWidth(300); //若是不設置寬度的話,默認取AnchorView的寬度,通常不是咱們想要的結果
listPopupWindow.setModal(true); //是否爲模態,影響到對back按鈕的處理
listPopupWindow.setAdapter(new ArrayAdapter<String>(this, R.layout.apt_v7_list_popup_window, R.id.apt_v7_tv, new String[]{
        "發起羣聊",
        "添加朋友",
        "掃一掃",
        "意見反饋"
}));
listPopupWindow.show();

##與PopMenu的對比事件

  1. PopMenu難以定製,ListPopupWindow的定製性更好
  2. ListPopupWindow不能自適應寬度
  3. PopMenu以面向菜單爲核心,能夠更方便的實現 禁用/開啓 功能

一個讓ListPopupWindow自適應寬度的方案,設置adapter後,檢測每一行的最大寬度,而後再來設置 ListPopupWindow 的寬度,有利有弊,本身取捨了。ip

關於菜單那的其餘實現方式:

  1. PopMenu

  2. PopupWindow + 自定義ContentView

  3. 頁面內View + 自定義touch事件以及按鍵事件處理

##demo demo

Android分享 Q羣:315658668