一、PopupWindow的概述
PopupWindow弹出框,与Dialog有点相似,不同点在与PopupWindow可以选择显示的位置,以及窗体的大小
常用的方法
PopupWindow(View) 构造方法传递一个View的对象参数,这个View使用inflater动态加载布局的方式生成
setWidth(ViewGroup.LayoutParams.MATCH_PARENT)设置窗体宽度
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT)设置窗体高度
setBackgroundDrawable(new ColorDrawable())设置窗体背景
setOutsideTouchable(true)设置窗体外部是否可触摸
setFocusable(true)设置窗体是否可以获取焦点
setTouchInterceptor()设置触摸事件
setOnDismissListener()当窗体调用dismiss方法时触发该监听事件
showAtLocation()设置窗体出现在布局的指定位置
showAsDropDown()设置窗体出现在指定View的相对位置
二、PopupWindow的实现
private void openNormalPop(){
LayoutInflater inflater=LayoutInflater.from(this);
View loginView= inflater.inflate(R.layout.login_dialog,null);
pWindow=new PopupWindow(loginView);
pWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
pWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
// 设置popupwindow不被键盘挡住
pWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
pWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
pWindow.setBackgroundDrawable(new ColorDrawable());
// pWindow.setOutsideTouchable(true);
pWindow.setFocusable(true);
setBackgroundAlpa(0.5f);
pWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
pWindow.dismiss();
return true;
}
return false;
}
});
pWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
setBackgroundAlpa(1f);
}
});
RelativeLayout relativeLayout= (RelativeLayout) findViewById(R.id.relative);
pWindow.showAtLocation(relativeLayout,Gravity.BOTTOM,0,0);
}
以上代码简单的实现在Activity的下方弹出PopupWindow,其中提供了一个自定义的方法setBackgroundAlpa来设置显示PopupWindow时的整个屏幕除窗体以外的背景色,以及关闭了PopupWindow后恢复为原背景色的方法
private void opendownPop(){
LayoutInflater inflater=LayoutInflater.from(PopupActivity.this);
View loginView= inflater.inflate(R.layout.login_dialog,null);
pWindow=new PopupWindow(loginView);
pWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
pWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
pWindow.setBackgroundDrawable(new ColorDrawable());
pWindow.setOutsideTouchable(true);
pWindow.setFocusable(true);
setBackgroundAlpa(0.5f);
pWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
pWindow.dismiss();
return true;
}
return false;
}
});
pWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
setBackgroundAlpa(1);
}
});
pWindow.showAsDropDown(findViewById(R.id.btndropdown),0,0);
}
以上方法是设置PopupWindow显现在按钮下(当然不仅仅是按钮,也可以是其他的View)
PopupWindow没有太多的深奥内容,主要是弹出PopupWindow时品屏幕背景色的变化的效果,并且PopupWindow的构造要传递一个动态加载布局的View