android popupwindow dialog区别,Android PopUpWindow使用详解

释放双眼,带上耳机,听听看~!

0d08079f652540336d7599383023090d.gif

一、概述

1、PopupWindow与AlertDialog的区别

最关键的区别是AlertDialog不能指定显示位置,只能默认显示在屏幕最中间(当然也可以通过设置WindowManager参数来改变位置)。而PopupWindow是可以指定显示位置的,随便哪个位置都可以,更加灵活。

2、PopupWindow的相关函数

第一步:最基本构造PopupWindow

View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);

PopupWindwo popWnd = PopupWindow (context);

popWnd.setContentView(contentView);

popWnd.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

popWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

拓展:也可以缩写成为两句话

View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);

PopupWindwo popWnd = new PopupWindow (contextView,ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

第二步:上面的代码基本就生成了一个简单的PopUpWindow,但是想要显示出来还需要以下方法

显示函数主要使用下面三个:

//相对某个控件的位置(正左下方),无偏移

showAsDropDown(View anchor):

//相对某个控件的位置,有偏移;xoff表示x轴的偏移,正值表示向左,负值表示向右;yoff表示相对y轴的偏移,正值是向下,负值是向上;

showAsDropDown(View anchor, int xoff, int yoff):

//相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移

showAtLocation(View parent, int gravity, int x, int y):

这里有两种显示方式:

1、显示在某个指定控件的下方

showAsDropDown(View anchor):

showAsDropDown(View anchor, int xoff, int yoff);

2、指定父视图,显示在父控件的某个位置(Gravity.TOP,Gravity.RIGHT等)

showAtLocation(View parent, int gravity, int x, int y);

第三步显示窗体

通过showAsDropDown显示出来,但是从哪里显示出来还没有定义,

有同学就会问难道不是在第一步布局文件显示的吗?

那只是显示的布局,并没有说在哪里显示,所以我们还是要加载主窗口,在主窗口显示

View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.main, null);

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

完整代码

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.pewm, null);

mPopWindow = new PopupWindow(contentView,

ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

//显示PopupWindow

View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值