项目用到的,实现了需要的功能,备用
// 屏幕的width
private int mScreenWidth;
// 屏幕的height
private int mScreenHeight;
//创建一个popwindows
private PopupWindow mPopupWindow;
//弹出pop的控件监听
@OnClick(R.id.service_firm)
public void service_firm(){
getPopupWindowInstance();
mPopupWindow.showAsDropDown(mService_firm);
}
/*
* 获取PopupWindow实例
*/
private void getPopupWindowInstance() {
if (null != mPopupWindow) {
mPopupWindow.dismiss();
return;
} else {
initPopuptWindow();
}
}
/*
* 创建PopupWindow
*/
private void initPopuptWindow() {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View view = layoutInflater.inflate(R.layout.pop_gongsi, null);
ListView mLv_gongsi = (ListView) view.findViewById(R.id.lv_list);
// 获取屏幕和PopupWindow的width和height
/*mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
mScreenHeight = getWindowManager().getDefaultDisplay().getHeight();*/
FuWuGongSiAdapter adapter_fuwugongsi = new FuWuGongSiAdapter(this);
mLv_gongsi.setAdapter(adapter_fuwugongsi);
adapter_fuwugongsi.setData(list_name);
adapter_fuwugongsi.notifyDataSetChanged();
mLv_gongsi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
GongSiBean gongsi = list_name.get(0);
mService_firm.setText(gongsi.getCompanyInfoShortname());
mPopupWindow.dismiss();
}
});
<pre name="code" class="java"> // 参数1:contentView 指定PopupWindow的内容
// 参数2:width 指定PopupWindow的width
// 参数3:height 指定PopupWindow的height
mPopupWindow = new PopupWindow(view,mService_firm.getWidth() , LinearLayout.LayoutParams.WRAP_CONTENT);
mPopupWindow.setTouchable(true);
mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("mengdd", "onTouch : ");
return false;
// 这里如果返回true的话,touch事件将被拦截,拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
}
});
// 设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框
mPopupWindow.setFocusable(true);
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.update();
mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
}
本文详细介绍了如何创建一个自定义的PopupWindow,包括获取屏幕尺寸、布局视图、初始化适配器和监听事件,确保在不同屏幕尺寸上都能正确显示。通过实例代码演示了如何实现在Android应用中灵活展示自定义内容的技巧。
347

被折叠的 条评论
为什么被折叠?



