Android中设置Dialog和自定义布局相同高度

说明:想要实现的效果是自定义布局和Dialog高度相同,则需要使用Dialog而不是AlertDialog,

如果使用AlertDialog则会出现初始自定义布局只是自适应高度并不是指定高度

java 复制代码
private void initDialogPopu(){
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int screenHeight = displayMetrics.heightPixels; // 屏幕总高度(像素)
        int height = screenHeight/5*2;
		//自定义布局
        View view1 = (View) this.getLayoutInflater().inflate(R.layout.popup_window, null);
        RecyclerView recyclerView = view1.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        DeviceAdapter adapter = new DeviceAdapter(this,list);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
		//指定自定义布局高度
		view1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
       //AlertDialog alertDialog = new AlertDialog.Builder(this,R.style.TransparentDialog).setView(view1).show();
	   //创建Dialog并指定style(背景透明样式)
        Dialog alertDialog = new Dialog(this,R.style.TransparentDialog);
        alertDialog.setContentView(view1);
        alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                
            }
        });
		//指定Dialog高度
        Window window = alertDialog.getWindow();
        if (window!=null)
            window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT,height);
        alertDialog.show();
    }

style样式

XML 复制代码
<style name="TransparentDialog" parent="Theme.AppCompat.Dialog">
        <item name="android:windowBackground">#00000000</item>
    </style>

popup_window自定义布局(根部局和列表都要高度设置 android:layout_height="match_parent")

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:padding="10dp"
    android:orientation="vertical">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:overScrollMode="never"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
相关推荐
用户69371750013841 小时前
Room 3.0:这次不是升级,是重来
android·前端·google
alexhilton4 小时前
Compose中的ContentScale:终极可视化指南
android·kotlin·android jetpack
Digitally6 小时前
2026 年 8 款安卓数据擦除软件和应用对比
android
杨忆6 小时前
android 11以上 截图工具类
android
粤M温同学7 小时前
Android Studio 中安装 CodeBuddy AI助手
android·ide·android studio
阿拉斯攀登7 小时前
【RK3576 安卓 JNI/NDK 系列 08】RK3576 实战(二):JNI 调用 I2C 驱动读取传感器数据
android·安卓ndk入门·jni方法签名·java调用c++·rk3576底层开发·rk3576 i2c开发
赶路人儿9 小时前
常见的mcp配置
android·adb
符哥20089 小时前
充电桩 WiFi 局域网配网(Android/Kotlin)流程、指令及实例说明文档
android·开发语言·kotlin
没有了遇见10 小时前
Android 项目架构之<用户信息模块>
android
Georgewu11 小时前
如何判断应用在鸿蒙卓易通或者出境易环境下?
android·harmonyos