天天看點

當顯示PopupWindow時如何設定透明度

在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>      

關于: