一、PopupWindow介绍(转自:http://www.2cto.com/kf/201205/131768.html)
Android的对话框有两种:PopupWindow和AlertDialog。它们的不同点在于:
AlertDialog的位置固定,而PopupWindow的位置可以随意
AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的
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等),可以设置偏移或无偏移
二、参考代码(转自:http://www.2cto.com/kf/201205/131768.html)
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/button01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="以自己为Anchor,不偏移" /> <Button android:id="@+id/button02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="以自己为Anchor,有偏移" /> <Button android:id="@+id/button03" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="以屏幕中心为参照,不偏移(正中间)" /> <Button android:id="@+id/button04" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="以屏幕下方为参照,下方中间" /> </LinearLayout>