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>
相关推荐
peakmain913 分钟前
基于 Hilt 实现 Android 网络库可插拔替换 Skill
android·架构·ai编程
黄林晴22 分钟前
Google I/O 2026 Android开发者速览
android·android studio
DogDaoDao1 小时前
Android 播放器开发:从零构建全功能视频播放器
android·ffmpeg·音视频·播放器·mediacodec·编解码
真鬼1232 小时前
【Unity安卓】Unity 嵌入 Android Studio 完整流程
android·unity·android studio
星间都市山脉2 小时前
Windows 环境 Android 系统 APK 签名操作文档
android·windows
shuaiqinke2 小时前
【分享】OrbitV工具箱| 手表手环全能适配 |表盘应用一键装
android·智能手机
子非吾喵2 小时前
HBuilder X本地打包的资源放到Android Studio本地打包的记录
android·ide·android studio
simplepeng13 小时前
我们都知道但总是忽略的5个Jetpack Compose细节
android·android jetpack
刮风那天14 小时前
Android 如何提高进程优先级避免被查杀?
android