Activity.java中代碼
//PopupWindow彈窗
private void showNoneEffect() {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vPopupWindow = inflater.inflate(R.layout.popupwindow, null, false);//引入彈窗佈局
popupWindow = new PopupWindow(vPopupWindow, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
//點擊外部彈出不消失
popupWindow.setFocusable(false);
popupWindow.setOutsideTouchable(false);
//設置透明背景佈局
setTransparentBg();
popu_sj_vip = vPopupWindow.findViewById(R.id.popu_sj_vip);
popu_sj_vip.setOnClickListener(this);
//引入依附的佈局
View parentView = LayoutInflater.from(this).inflate(R.layout.activity_setting, null);
//相對於父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以設置偏移或無偏移
popupWindow.showAtLocation(parentView, Gravity.CENTER, 0, 0);
}
private void setTransparentBg() {
// 設置背景顏色變暗
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.7f;//調節透明度
getWindow().setAttributes(lp);
//監聽彈窗
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
//彈窗關閉 dismiss()時恢復原樣
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 1f;
getWindow().setAttributes(lp);
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//攔截彈窗外部點擊事件
if (popupWindow != null && popupWindow.isShowing()) {
return false;
}
return super.dispatchTouchEvent(ev);
}
彈窗佈局文件popupwindow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:paddingTop="28dp"
android:paddingBottom="40dp"
android:paddingLeft="56dp"
android:paddingRight="56dp"
android:background="@drawable/radius_border">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="假密碼"
android:textColor="#ff000000"
android:textSize="19sp"
/>
<TextView
android:layout_marginTop="36dp"
android:layout_width="164dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="這是會員功能,免費解鎖請升級到會員"
android:textColor="#ff333333"
android:textSize="15sp"
/>
<LinearLayout
android:id="@+id/popu_sj_vip"
android:layout_width="160dp"
android:layout_height="35dp"
android:layout_marginTop="40dp"
android:orientation="vertical"
android:background="@drawable/btn_bg"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="升級到會員"
android:textColor="#ffffffff"
android:textSize="16sp"
/>
</LinearLayout>
</LinearLayout>