Android如何强制默认屏幕密度 [英] Android how to force screen density by default

查看:61
本文介绍了Android如何强制默认屏幕密度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过设置/显示"放大屏幕,我发现我的 Galaxy s9+ 的屏幕密度从 430 dpi 变为 600dpi 以上.

By magnifying the screen by "Settings / Displays", I've found that my galaxy s9+'s screen density changes to 430 dpi to somewhere over 600dpi.

这会使布局和图像更改为 xxhdpi 到 xxxhdpi.

This makes the layout and images to change to xxhdpi to xxxhdpi.

如果我有一个固定大小为 16dp 的 textView,

If I have a textView which has the fixed size of 16dp,

在 xxhdpi 中为 16 * 3 px,在 xxxhdpi 中将变为 16 * 4 px.

it was 16 * 3 px in xxhdpi, and will become 16 * 4 px in xxxhdpi.

这使得我的布局(当然是来自 editTexts 或 textViews 的文本)变得更大,因为设备的实际密度永远不会改变,这是谷歌(或制造商 samsumg)打算用于此功能的.

This makes my layout(of course texts from editTexts or textViews) to become much bigger since the actual density of the device never changes, which google(or the maker samsumg) intended for this function.

但我不希望这种情况发生在我的应用中.

But I do not want this to happen in my app.

我已经尝试通过这样做来修复它;

I've tried to fix it by doing this ;

Configuration configuration = activity.getResources().getConfiguration();

if (configuration.densityDpi != 430) { 
                configuration.densityDpi = 430;    
}

DisplayMetrics metrics = activity.getResources().getDisplayMetrics();
WindowManager wm = (WindowManager) activity.getSystemService(activity.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = configuration.densityDpi * metrics.density;
activity.getResources().updateConfiguration(configuration, metrics);

这会强制屏幕密度变为 430,并且在 Galaxy s9+ 上运行良好.但是,事实上,并非所有设备的默认密度都是 430.

This forces the screen density to become 430 and works fine on galaxy s9+. But, as a matter of fact, the default density will not be 430 for all devices.

如何确定运行我的应用程序的设备的默认密度?

How can I figure out the default density of the device which runs my application?

或者是否有配置可以忽略我的应用程序的放大效果?

Or is there a configuration to ignore the magnify effect for my application?

推荐答案

这似乎对我有用.

        DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();

        int snap = 20;
        float exactDpi = (displayMetrics.xdpi + displayMetrics.ydpi) / 2;
        float dpi = displayMetrics.densityDpi;

        if (dpi - exactDpi > snap) {

            int targetDpi = (int) (Math.ceil(exactDpi / snap) * snap);

            Configuration config = activity.getResources().getConfiguration();

            ErrorController.showMessage("adjustDisplayScale : " + config.densityDpi);

            ErrorController.showMessage("targetDpi : " + targetDpi);


            displayMetrics.densityDpi = targetDpi;
            config.densityDpi = targetDpi;
            displayMetrics.setTo(displayMetrics);
            config.setTo(config);
            activity.getResources().updateConfiguration(config, displayMetrics);
        }

这篇关于Android如何强制默认屏幕密度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆