动态添加PopupWindow

动态添加PopupWindow的方法
private void showPopupWindow() {
LayoutInflater inflater = LayoutInflater.from(this) ;
View view = inflater.inflate(R.layout.popup_check, null);
mAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1,resIds_Chenk);
ListView mListView = (ListView) view.findViewById(R.id.popup_listview);
mListView.setAdapter(mAdapter);
final PopupWindow mPopupWindow = new PopupWindow(view,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mPopupWindow.setFocusable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
R.drawable.popup_window_bg,null));
mPopupWindow.showAsDropDown(mCategory,0, 0);
mPopupWindow.update();
mListView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
if (mPopupWindow.isShowing()) {
mCategory.setText(resIds_Chenk[position]);
mPopupWindow.dismiss();
}
}
});
}


R.layout.popup_check的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/popup_list_bg"
android:orientation="vertical" >

<ListView
android:id="@+id/popup_listview"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:cacheColorHint="#000000"
android:divider="@color/white"
android:dividerHeight="1dp"
android:fadingEdge="none"
android:listSelector="@drawable/listitem_selector"
/>

</LinearLayout>


注释:

设置进场动画:
mPop.setAnimationStyle(R.style.AnimationPreview);//设置动画样式

mPop.setOutsideTouchable(true);//这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。当然这里很明显只能在Touchable下才能使用。

当有mPop.setFocusable(false);的时候,说明PopuWindow不能获得焦点,即使设置设置了背景不为空也不能点击外面消失,只能由dismiss()消失,但是外面的View的事件还是可以触发,back键也可以顺利dismiss掉。当设置为popuWindow.setFocusable(true);的时候,加上下面两行设置背景代码,点击外面和Back键才会消失。

mPop.setFocusable(true);
需要顺利让PopUpWindow dimiss(即点击PopuWindow之外的地方此或者back键PopuWindow会消失);PopUpWindow的背景不能为空。必须在popuWindow.showAsDropDown(v);或者其它的显示PopuWindow方法之前设置它的背景不为空:

mPop.setBackgroundDrawable(new ColorDrawable(0));

mPop.showAsDropDown(anchor, 0, 0);//设置显示PopupWindow的位置位于View的左下方,x,y表示坐标偏移量

mPop.showAtLocation(findViewById(R.id.parent), Gravity.LEFT, 0, -90);(以某个View为参考),表示弹出窗口以parent组件为参考,位于左侧,偏移-90。

mPop.setOnDismissListenerd(new PopupWindow.OnDismissListener(){})//设置窗口消失事件

posted @ 2016-05-20 09:47  Egg丶牛皮  阅读(1219)  评论(0编辑  收藏  举报