Android之PopupWindow弹出对话框


Android的对话框常用的有两种:PopupWindow和AlertDialog。PopupWindow顾名思义为弹出菜单,不同于AlertDialog对话框,PopupWindow弹出的位置可以很多变化,按照有无偏移分,可以分为无偏移和偏移两种;按照参照类型不同又可以分为两种:相对某个控件(Anchor锚)的位置和父容器内部的相对位置。具体如下:

函数 简介
showAsDropDown(View anchor) 相对某个控件的位置(正左下方),无偏移
showAsDropDown(View anchor, int xoff, int yoff) 相对某个控件的位置,有偏移(正数表示下方右边,负数表示(上方左边))
showAtLocation(View parent, int gravity, int x, int y) 父容器容器相对位置,例如正中央Gravity.CENTER,下方Gravity.BOTTOM等

下面是运行程序截图:

   

     

             

程序代码:

布局:main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:id="@+id/layout"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent"  
  7.     >  
  8. <TextView    
  9.     android:id="@+id/tv_showText"  
  10.     android:layout_width="fill_parent"    
  11.     android:layout_height="wrap_content"    
  12.     android:gravity="center"  
  13.     android:text="@string/hello"  
  14.     android:textSize="22px"  
  15.     />  
  16.        
  17. <Button  
  18.     android:id="@+id/bt_PopupWindow1"  
  19.     android:text="以自己为Anchor,不偏移"  
  20.     android:layout_width="fill_parent"    
  21.     android:layout_height="wrap_content"  
  22.     />     
  23.   
  24. <Button  
  25.     android:id="@+id/bt_PopupWindow2"  
  26.     android:text="以自己为Anchor,正下方"  
  27.     android:layout_width="fill_parent"    
  28.     android:layout_height="wrap_content"  
  29.     />     
  30.        
  31. <Button  
  32.     android:id="@+id/bt_PopupWindow3"  
  33.     android:text="以屏幕中心为参照,不偏移(正中间)"  
  34.     android:layout_width="fill_parent"    
  35.     android:layout_height="wrap_content"  
  36.     />     
  37.   
  38. <Button  
  39.     android:id="@+id/bt_PopupWindow4"  
  40.     android:text="以屏幕下方为参照,下方中间"  
  41.     android:layout_width="fill_parent"    
  42.     android:layout_height="wrap_content"  
  43.     />     
  44.        
  45.      
  46. </LinearLayout>  
  • 1
  • 2
  • 下一页

相关内容