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>
相关推荐
故渊at19 小时前
第二板块:Android 四大组件标准化学理 | 第六篇:四大组件架构总论与 Manifest 规范
android·架构·zygote·manifest·四大组件
Jinkxs19 小时前
Python基础 - 文件的写入操作 write与writelines方法
android·服务器·python
jason.zeng@150220720 小时前
(第二讲)Android开发取摄像头流的基础(ImageAnalysis)
android
敲代码的瓦龙21 小时前
操作系统?Android与Linux!!!
android·linux·运维
愚公搬代码21 小时前
【愚公系列】《移动端AI应用开发》017-Android端应用开发(网络通信与API集成)
android·人工智能
say_fall21 小时前
可编程中断控制器8259A工作方式超详细解析
android·开发语言·学习·硬件架构·硬件工程
甜瓜看代码1 天前
SystemUI 启动与组成机制
android·源码·源码阅读
黄林晴1 天前
Kotlin 2.4.0 正式稳定!Android 升级、Compose、KMP 全变化详解
android·kotlin
恋猫de小郭1 天前
Android 官方给 Compose 搞了个不需要 UI 环境的 Composable
android·前端·flutter
珊瑚里的鱼1 天前
C++的强制类型转换
android·开发语言·c++