本文共 4512 字,大约阅读时间需要 15 分钟。
Android应用中经常会弹出一个窗体,进行一些操作,比如说分享、选择城市等等,类似于AlertDialog,下面将详细讲解PopupWindow。
PopupWindow的构造方法,官方给出的有9种,项目中常用的只有最后两种
PopupWindow(Context context)
PopupWindow(Context context, AttributeSet attrs)
PopupWindow(Context context, AttributeSet attrs, int defStyleAttr)
PopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
PopupWindow()
PopupWindow(View contentView)
PopupWindow(int width, int height)
PopupWindow(View contentView, int width, int height)
View view=getLayoutInflater().inflate(R.layout.window, null);PopupWindow mPop =new PopupWindow(view,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
PopupWindow(View contentView, int width, int height, boolean focusable)
Create a new popup window which can display the contentView. 创建一个自定义宽度、高度、显示内容、是否有焦点的弹窗。 contentView:自定义的弹窗显示内容 width:弹窗宽度 height:弹窗高度 focusable:是否有焦点,true:有焦点;false:无焦点(默认为false,与第8中构造方法效果相同) 举个栗子View view=getLayoutInflater().inflate(R.layout.window, null);PopupWindow mPop =new PopupWindow(view,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
PopupWindow一般有两种展示方法,用showAsDropDown()和showAtLocation()两种方法实现。一般参数有两种,有偏移和无偏移。
官方的方法如下 showAsDropDown() -showAsDropDown(View anchor, int xoff, int yoff, int gravity)
- showAsDropDown(View anchor, int xoff, int yoff)
- showAsDropDown(View anchor)
anchor可以理解为锚,弹窗显示在anchor下面,xoff为X轴偏移量,yoff为Y轴偏移量,gravity为显示方式 上栗子 - mPop.showAsDropDown(anchor);
弹窗显示在anchor正下方,无任何偏移。 - mPop.showAsDropDown(anchor,xoff,yoff);
弹窗在anchor下方显示,X轴偏移xoff,Y轴偏移yoff。 - mPop.showAsDropDown(anchor,xoff,yoff,Gravity.CENTER);
弹出在anchor下方居中显示,同时X轴偏移xoff,Y轴偏移yoff。 showAtLocation()
-showAtLocation(View parent, int gravity, int x, int y)
按函数名来理解,很容易看出该函数的意义,即在某个位置显示弹窗,我们要做的就是为弹窗设置Location。 parent:弹窗显示的父容器 gravity:显示方式 x:X轴偏移量 y:Y轴偏移量 栗子来啦 mPop.showAtLocation(PopWindow.this.findViewById(R.id.rl), Gravity.TOP | Gravity.LEFT, 20, 20);
在屏幕顶部|居右,X轴偏移20,Y轴偏移20;
这里实现一个常见的分享弹窗,点击弹窗外面或者点击back键,关闭弹窗
两个布局文件,一个主界面布局文件、一个弹框内容布局文件 activity_main.xmlpopup_share.xml
重新activity的onCreate方法
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); popupView= getLayoutInflater().inflate(R.layout.popup_share, null); mPop = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true); mPop.setBackgroundDrawable(new ColorDrawable(0)); btn1=(Button) findViewById(R.id.btn1); btn1.setOnClickListener(this); btn2=(Button) findViewById(R.id.btn2); btn2.setOnClickListener(this); }
两种显示方法的触发事件
@Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn1: mPop.showAsDropDown(btn1); break; case R.id.btn2: mPop.showAsDropDown(btn2,290,-50); break; default: break; } }