1.PopupWindow的常用方法:
简单的demo
MainActivity中创建buttonclick方法
public void buttonclick(View view) {
View popupView = getLayoutInflater().inflate(R.layout.popupview,null);
Button btn1 = popupView.findViewById(R.id.btn1);
PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);
popupWindow.showAsDropDown(view,view.getWidth(),-view.getHeight());
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
popupWindow.dismiss();
}
});
}
activity_main中创建button
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="弹出框"
android:onClick="buttonclick"/>
popupview中再创建一个button
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="退出"
android:textSize="18sp"/>
效果图:
点击前:
点击后:
点击弹出框和退出都可以取消弹出框
PopupWindow的配置参数详解
设置内容View
setContentView(View contentView)
可以用这个方法在实例化后重新配置需要的view
设置PopupWindow宽度与高度
setWidth(int width)
setHeight(int height)
也可以用这个2个方法在实例化后在重新配置需要的宽度与高度
设置PopupWindow背景
setBackgroundDrawable(Drawable background)
简单的demo
public void buttonclick(View view) {
View popupView = getLayoutInflater().inflate(R.layout.popupview,null);
Button btn1 = popupView.findViewById(R.id.btn1);
PopupWindow popupWindow = new PopupWindow(popupView, 200,300,true);
popupWindow.setOutsideTouchable(true);
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_launcher_background));
popupWindow.showAsDropDown(view,view.getWidth(),-view.getHeight());
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
popupWindow.dismiss();
}
});
效果图
设置外部点击退出
setOutsideTouchable(boolean touchable)
设置PopupWindow可聚焦
setFocusable(boolean focusable)
设置了可聚焦后,返回back键按下后,不会直接退出当前activity而是先退出当前的PopupWindow
设置弹窗弹出的动画高度
setElevation(float elevation)
没有设置,弹窗的弹出动画效果位置就只会在控件附件,但是设置后弹窗的起始动画位置就变更远了
popupWindow.setElevation(1000f);//我将动画位置设置为1000f
注:使用了以后可能会有点卡顿
设置PopupWindow叠放效果
setOverlapAnchor(true);
设置PopupWindow可触摸
setTouchable(true);
设置PopupWindow监听拦截指定触摸事件
popupWindow.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//如果返回true,不会向下传递到内容view里
return false;
}
});
设置PopupWindow覆盖状态栏或者超过屏幕尺寸
允许弹出窗口扩展到屏幕范围之外。默认情况下,窗口被裁剪到屏幕边界。将其设置为false将允许精确定位窗口
popupWindow.setClippingEnabled(false);
设置PopupWindow监听取消事件
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
}
});