PopWindows详解
1、pop布局(activity_pop.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android";
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button" />
<Button
android="@+id/button_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button" />
</LinearLayout>
2、初始化PopupWindow:
LayoutInflater inflater = LayoutInflater.from(getApplication());
// 获取当面界面的主布局
View rootView = MainActivity.this.findViewById(R.id.ll_main);
View popView = inflater.inflate(R.layout.activity_pop, null, false);
pop = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
// 需要设置一下此参数,点击外边可消失
// 如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是Back键都无法dismiss弹框
pop.setBackgroundDrawable(new BitmapDrawable());
// 设置此参数获得焦点,否则无法点击
pop.setFocusable(true);
// 设置点击窗口外边窗口消失
pop.setOutsideTouchable(true);
3、弹出PopupWindow:
//在当前界面正下方显示
pop.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
// 显示在相对于view的左下方(这个左下方是在屏幕的左下方)
pop.showAtLocation(view, Gravity.TOP | Gravity.RIGHT, 0, 0);
// 用来保存按钮view的坐标,location[0]是X轴,location[1]是Y轴
int[] location = new int[2];
Log.d("Taonce", "location:" + location.toString());
view.getLocationOnScreen(location);
// 在按钮view的左边
pop.showAtLocation(view, Gravity.NO_GRAVITY, location[0] - view.getWidth(), location[1]);
// 左上方
pop.showAtLocation(view, Gravity.NO_GRAVITY, location[0] - view.getWidth(), location[1] - view.getHeight());
// 左下方
pop.showAtLocation(view, Gravity.NO_GRAVITY, location[0] - view.getWidth(), location[1] + view.getHeight());
这里我只列举了几种,其他的可以自己试验下。
注意:上面的view是Button是onClick(View view)中的view。
4、pop的点击事件:
Button button_one = popView.findViewById(R.id.button_one);
button_one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplication(),"on click one",Toast.LENGTH_SHORT);
// 记得dismiss掉
pop.dismiss();
}
});