android:PopupWindow的使用场景和注意事项

来源:互联网 发布:mac系统的游戏进程 编辑:程序博客网 时间:2024/04/29 02:06

1.PopupWindow的特点

借用Google官方的说法:

A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.

也就是说,popupwindow是activity上方的一个悬浮容器,它可以显示任意的视图View,很霸气的样子。下面看一下,它如何使用的。

2.初始化PopupWindow的一些特性

举例:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. PopupWindow popupWindow = new PopupWindow(getApplicationContext());  
  2.         popupWindow.setContentView(contentView);//可以设置任意的View  
  3.         popupWindow.setWidth(LayoutParams.WRAP_CONTENT);//设置宽度  
  4.         popupWindow.setHeight(LayoutParams.WRAP_CONTENT);//高度  
  5.         popupWindow.setAnimationStyle(R.anim.abc_fade_in);//显示的动画  
  6.         popupWindow.setFocusable(true);//设置是否获取焦点  

其中,contentView是你想要显示的View。

3.PopupWindow的显示和隐藏

显示的方法:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public void showAtLocation (View parent, int gravity, int x, int y)  
  2. Added in API level 1  
  3. Display the content view in a popup window at the specified location. If the popup window cannot fit on screen, it will be clipped. See WindowManager.LayoutParams for more information on how gravity and the x and y parameters are related. Specifying a gravity of NO_GRAVITY is similar to specifying Gravity.LEFT | Gravity.TOP.  
  4.   
  5. Parameters  
  6. parent  a parent view to get the getWindowToken() token from  
  7. gravity the gravity which controls the placement of the popup window  
  8. x   the popup's x location offset  
  9. y   the popup's y location offset  

popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);//设置居中

popupWindow.showAtLocation(contentView, Gravity.NO_GRAVITY, x, y);//显示窗口的以(x,y)为左上角的位置


隐藏:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. if (popupWindow != null  
  2.                 && popupWindow.isShowing()) {  
  3.             popupWindow.dismiss();  
  4.             popupWindow = null;  
  5.         }  


相关:注意,在计算view的位置时:

Android里面提供了一些方法可以获取View在屏幕中的位置。
1).getLocationOnScreen ,计算该视图在全局坐标系中的x,y值,获取在当前屏幕内的绝对坐标(该值从屏幕顶端算起,包括了通知栏高度)。 
2).getLocationInWindow ,计算该视图在它所在的widnow的坐标x,y值。
3)getLeft , getTop, getBottom, getRight,  这一组是获取相对在它父亲布局里的坐标。


相关:popupwindow动画:http://blog.csdn.net/wl455624651/article/details/7798879

0 0