popupWindow中用listView作为数据绑定显示

  • Post author:
  • Post category:其他


本文主要是在工工作中遇到的一些问题总结,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



版权声明:本文为ling9400原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。