- PopWindow和AlertDialog的使用非常的相似
- 效果图如下:

- 自定义布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView_exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:gravity="center"
android:background="#004400"
android:layout_gravity="center"
android:textSize="40sp"
android:text="退出"/>
<TextView
android:id="@+id/textView_cancal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:background="#990055"
android:layout_gravity="center"
android:textSize="40sp"
android:gravity="center"
android:text="取消"/>
</LinearLayout>
if (!popupWindow.isShowing()){
popupWindow = new PopupWindow()
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_popwindow, null)
TextView textView_exit = (TextView) view.findViewById(R.id.textView_exit)
TextView textView_cancal = (TextView) view.findViewById(R.id.textView_cancal)
textView_cancal.setOnClickListener(this)
textView_exit.setOnClickListener(this)
popupWindow.setContentView(view)
popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT)
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT)
// View rootView=LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main,null)
// popupWindow.showAtLocation(rootView,Gravity.BOTTOM,0,0)
popupWindow.showAsDropDown(button,0,0)
}
- 可以通过判断popupWindow.isShowing()方法,来确定是否已经打开了popWindow,以避免popWindow的重复打开
- 对自定义控件的点击事件的处理我并未上传,仅仅是一个吐司提示,读者请自行尝试。
- 第一种显示popWindow的方法
popupWindow.showAsDropDown(button,0,0)
- 方法表示popWindow放置在哪个控件的下方,以及x和y的偏移量。
- 第二种显示popWindow的方法
View rootView=LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main,null)
popupWindow.showAtLocation(rootView,Gravity.BOTTOM,0,0)
- 需要加载popWindow的所在的布局的实例,然后设置其父控件,对齐方式,以及x、y的偏移量