popupWindow中用listView作爲數據綁定顯示

本文主要是在工工作中遇到的一些問題總結,PS:如有不正確的地方請指出來,謝謝!

首先,需求就是做一個類似微信公衆號一樣的界面,我做出來的效果如下圖所示,


下面的菜單按鈕像微信公衆號一樣的popupwindow,因爲菜單是從服務器上獲取的,用過微信公衆號的朋友也知道微信公衆號這個菜單是可以編輯的,也就是說菜單數量是可變的,不確定的,所以這裏只能用listView作爲popupwindow的內容界面。

popwindow.xml內容

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
android:paddingBottom="50dp"
    android:orientation="vertical" >


    <ListView
        android:id="@+id/lvPopwindow_direct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scrollbars="@null"
        android:padding="2dp"
        android:background="@drawable/bg_pop_listview"
        android:listSelector="@drawable/selector_listview"
        >
    </ListView>


</LinearLayout>


裏面其實就是一個listView,但注意我的linearLayout裏面有一個paddingBottom屬性,它的值就是你下面菜單的高度,listView的padding主要是做一個邊框用的,沒什麼多大問題。

最後,我顯示popwindow時的代碼

protected void showPopWindow(final View v, List<String> data) {

WindowManager wm = (WindowManager) myContext.getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
// int srceenHeight = wm.getDefaultDisplay().getHeight();
if (popupWindow == null || lvPop == null ) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
View popView = layoutInflater.inflate(R.layout.direct_popupwindow, null);
lvPop = (ListView) popView.findViewById(R.id.lvPopwindow_direct);
popView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
popupWindow = new PopupWindow(popView, 2*width/5, LayoutParams.WRAP_CONTENT);
}

//設置adapter
AdapterDirectPop adapterDirectPop = new AdapterDirectPop(myContext, data);
lvPop.setAdapter(adapterDirectPop);


popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(false);
// 這個是爲了點擊“返回Back”也能使其消失,並且並不會影響你的背景
popupWindow.setBackgroundDrawable(new BitmapDrawable());
//仿微信的popwindow  水平偏移根據popwindow的寬度改變    屏幕寬度的三分之一,水平偏移距離必須165以上纔會顯示距離
// popupWindow.showAsDropDown(v,-210,1);

int[] location = new int[2];
v.getLocationOnScreen(location);
popupWindow.getContentView().measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int w = popupWindow.getContentView().getMeasuredWidth();
//根據屏幕寬度計算出比例值srceenHeight*21/32
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0] - w/4 , location[1]);

}

這裏主要是因爲是顯示在點擊的View的上方,而不是下方,所以只能用showAtLocation,不能用showAsDropDown這個方法,這樣就解決了popupwindow中用listView作爲數據顯示的問題。該代碼有一個BUG就是設置了paddingBottom之後,你顯示了popupwindow後你再次點擊同一個Views 是沒用的,因爲你點擊的那個View被透明層覆蓋了,不能再次獲得焦點,所以也不能獲得點擊事件,必須點擊其他地方popupwindow纔會消失。PS:能解決這個問題的朋友請跟我說下,謝謝了!或者你有更好的辦法來解決我這種情況的也可以聯繫我,一起探討下。

demo下載地址:http://download.csdn.net/detail/ling9400/9548293

發佈了27 篇原創文章 · 獲贊 8 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章