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>
相关推荐
墨天梦3 小时前
B17_LifecycleLiveData与Flow
android·kotlin
_祝你今天愉快5 小时前
UI核心 - 绘制流程(测量、布局、绘制)
android
冬奇Lab6 小时前
LLM 驱动的自动化测试系列(07):移动端自动化(三)——Mobile-Agent-v3 与自研 GUI-Owl 模型路线
android·人工智能·测试
leobertlan9 小时前
痛苦系列 | DSP-02 频域切片:DTFT与DFT的探索
android·后端
leobertlan10 小时前
痛苦系列 | DSP-01 从连续到离散:DSP基础与采样
android·后端
事圆则缓12 小时前
Android 视频压缩上传实战:从 content Uri、转码到断点续传
android
冉冉同学15 小时前
AI Agent 开始操作真实手机:移动端自动化的 3 个新考点
android·ai编程
帅得不敢出门16 小时前
Android Framework关闭软件低电关机功能测试PMIC低电保护
android
恋猫de小郭16 小时前
Flutter + EmbeddingGemma 2,谷歌发布完全端侧的 AI Edge Foresight
android·前端·flutter
墨天梦18 小时前
B16_Material主题与可访问交互
android·kotlin·交互