Android对话框的大小设置

本文介绍了如何在Android中动态修改对话框的大小,通过代码设置对话框尺寸,并提供了参考的像素与密度独立像素(dp)的转换方式,适用于不同设备和需求的适配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dialog的大小除了可以引用自定义布局外, 还可以通过代码进行固定:

            mDialog.show();
            // Window window = mDialog.getWindow();  
            // window.getDecorView().setPadding(0, 0, 0, 0);

            WindowManager.LayoutParams attrs = mDialog.getWindow().getAttributes();
            //attrs.setTitle("Title");
            attrs.width = WindowManager.LayoutParams.WRAP_CONTENT;// attrs.width =580;
            attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;// attrs.height = 600;
            mDialog.getWindow().setAttributes(attrs);
还有一种, 可以通过手机设备的像素密度进行动态设置对话框的宽与高, 不至于同样像素的内容在分辨率不同的设备上出现不同的效果:
private static void setLayoutParams(Context context,Dialog dialog){
         WindowManager.LayoutParams attrs = dialog.getWindow().getAttributes();
         final float scale = context.getResources().getDisplayMetrics().density;
         attrs.width = (int)(193*scale+0.5f);
         attrs.height =(int)(200*scale+0.5f);
         dialog.getWindow().setAttributes(attrs);
    }

文中所给的193与200是通过测试,显示的一个比较好的值. 不同的设备与不同的需求可以进行数值的调试.

参考以下资料:
1、px :是屏幕的像素点
2、dp :一个基于density的抽象单位,如果一个160dpi的屏幕,1dp=1px
3、转换方式如下

public class DensityUtil {  

    /** 
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素) 
     */  
    public static int dip2px(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  

    /** 
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp 
     */  
    public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
}

滴~学生卡

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值