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>
相关推荐
157092511342 小时前
ViewBinding与DataBinding区别与选型
android
小乖写代码3 小时前
49款开源Android小游戏
android·游戏
三少爷的鞋4 小时前
小团队的最优解:单 Module + 包内 Clean 架构
android
爱和冰阔落4 小时前
【Linux】两个毫无关系的进程怎么通信?命名管道 FIFO 从原理到 Server/Client 实战
android·linux·数据库·c++·vim
Android-Flutter4 小时前
kotlin 协程 - 核心概念
android·kotlin
年小个大13 小时前
受 go-zero 启发,我给 Flutter 写了一套 CLI 脚手架
android·flutter·架构
Android-Flutter14 小时前
为什么说ActivityThread是主线程?
android·kotlin
余额瞒着我当琳16 小时前
C++模板初阶与STL初探
android·java·c++
知行合一。。。19 小时前
DeepAgents--01--Agent和OpenClaw的相关概念
android·数据库
汪海游龙20 小时前
告别 Play Console 手动上传:从模拟器截图到自动发版的完整流水线
android·ci/cd·github