安卓自定义Dialog透明
1.自定义MyDialog,继承Dialog
class MyDialog extends Dialog {
private View contentView;
public MyDialog(@NonNull Context context, @StyleRes int themeResId) {
super(context, themeResId);
// 自已定义Dialog的布局
contentView = LayoutInflater.from(context).inflate(R.layout.popwindow_layout,null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(contentView);
}
//提供外部获取View的方法
public View getContentView() {
return contentView;
}
}
2.自定义Dialog中要加载的布局popwindow_layout
<?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:background="@drawable/popdialog_bg_selector"
android:orientation="vertical">
<!-- 这里自定义Dialog的布局-->
<ListView
android:layout_width="350dp"
android:layout_height="350dp"
android:divider="@color/colorPrimaryDark"
android:dividerHeight="1dp">
</ListView>
</LinearLayout>
3.在values–styles中定义透明Dialog主题
<style name="DialogTheme_NoBackground" parent="android:style/Theme.Dialog">
<item name="android:background">@color/transparent</item>
<item name="android:windowBackground">@color/transparent</item> <!--背景透明-->
<item name="android:windowNoTitle">true</item> <!--无标题-->
<item name="android:windowFullscreen">false</item> <!--全屏-->
<item name="android:windowContentOverlay">@null</item> <!--定义contentoverlay的背景-->
<item name="android:windowIsTranslucent">true</item> <!--半透明-->
</style>
4.在values–colors中定义Color,设置背景透明度
//全透明色
<color name="transparent">#00000000</color>
5.创建Dialog ,显示在界面上
//创建Dialog,并设置主题
MyDialog popDialog = new MyDialog(MainActivity.this ,R.style.DialogTheme_NoBackground);
//是否允许手动退出
popDialog.setCancelable(true);
popDialog.show();