PopupWindow那些事


转载自:PopUpWindow使用详解(一)——基本使用

PopupWindow的构造函数

//方法一:
public PopupWindow (Context context)
//方法二:
public PopupWindow(View contentView)
//方法三:
public PopupWindow(View contentView, int width, int height)
//方法四:
public PopupWindow(View contentView, int width, int height, boolean focusable)

其中contentView是设置的布局

PopupWindow的常用方法

显示PopupWindow

mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

将PopupWindow放在父容器中,显示在BOTTOM的位置

显示窗体showAsDropDown

image-20211001160832054

mMenuTv = (TextView)findViewById(R.id.menu);
mPopWindow.showAsDropDown(mMenuTv);
//mPopWindow.showAsDropDown(View anchor, int xoff, int yoff)

其中mMenuTv是菜单控件

为PopupWindow添加动画

mPopWindow.setAnimationStyle(R.style.contextMenuAnim);

为菜单添加阴影

  1. 在布局外层再包一层RelativeLayout,并添加半透明背景android:background=”#66000000”

    此时设置的android:layout_width和android:layout_height是无意义的,会重新设置

  2. 添加代码

    mPopWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
    mPopWindow.setHeight(ViewGroup.LayoutParams.FILL_PARENT);
    

setTouchable(boolean touchable)

设置PopupWindow是否响应touch事件,默认是true,如果设置为false,所有touch事件无响应,包括点击事件

setFocusable(boolean focusable)

该函数的意义表示,PopupWindow是否具有获取焦点的能力,默认为False。一般来讲是没有用的,因为普通的控件是不需要获取焦点的,而对于EditText则不同,如果不能获取焦点,那么EditText将是无法编辑的。

setOutsideTouchable(boolean touchable)

这个函数的意义,就是指,PopupWindow以外的区域是否可点击,即如果点击PopupWindow以外的区域,PopupWindow是否会消失。

mPopWindow.setBackgroundDrawable(new BitmapDrawable());
mPopWindow.setOutsideTouchable(true);

加上mPopWindow.setBackgroundDrawable(new BitmapDrawable());才可以点击

setBackgroundDrawable(Drawable background)

只有加上它之后,PopupWindow才会对手机的返回按钮有响应:即,点击手机返回按钮,可以关闭PopupWindow;如果不加setBackgroundDrawable()将关闭的PopupWindow所在的Activity.

可以填充进去各种Drawable,比如new BitmapDrawable(),new ColorDrawable(),等;

设置各个控件的点击响应

TextView tv1 = (TextView)contentView.findViewById(R.id.pop_computer);
tv1.setOnClickListener(this);

Author: Xi Chen
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Xi Chen !
评论
  TOC