在android中展示PopupWindow时设置透明背景的流程:
1、点击view,更改view的状态(展示状态),然后弹出popwindow。弹出popwindow的同时,设置背景为半透明。
2、操作或查看后关闭,关闭的同时回复view状态(原始状态),同时设置背景为不透明状态。
例子:
private MyPopupWindow popupWindow;
private void showPopupWindow(int type) {
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();//如果正在显示,关闭弹窗。
} else {
changeViewColor(type, true);//设置弹出时点击按钮状态
backgroundAlpha(0.8f);//设置弹出时背景半透明
popupWindow = new MyPopupWindow(this, line, type);//line 表示在哪个view下面显示
popupWindow.setMyPopupWindowLisenter(presenter);//设置popupwindow的回调
popupWindow.initData(dataList);//初始化popupwindow数据
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {//监听释放popupWindow
@Override
public void onDismiss() {
changeViewColor(type, false);//恢复按钮状态
backgroundAlpha(1f);//恢复不透明
}
});
}
}
private void backgroundAlpha(float f) {//透明函数
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = f;
getWindow().setAttributes(lp);
}
此应用的缺点:
显示弹出popupwindow的时候,整个背景色都是半透明。
如果想让popupwindow上半部分透明,下半部分不透明,需要修改popupwindow的布局,添加半透明填充view,如下:
代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
>
<LinearLayout
android:id="@+id/ll_operate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/v_pop"
android:background="#FFFFFF">
</LinearLayout>
<View
android:id="@+id/viewBG"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#60000000"
android:layout_below="@id/ll_operate"
android:visibility="visible" />
</RelativeLayout>
关于: