如何确定屏幕宽度DP或浸方面在运行时的Andr​​oid?宽度、屏幕、方面、DP

2023-09-13 02:23:36 作者:我要的是你的心,不是人

我需要code中的机器人部件的布局采用DIP / DP(在Java文件)。在运行时,如果我code,      INT像素= this.getWindowManager()getDefaultDisplay()的getWidth();

I need to code the layout of the android widgets using dip/dp (in java files). At runtime if I code, int pixel=this.getWindowManager().getDefaultDisplay().getWidth();

这回屏幕宽度的像素(PX)。将其转换为DP,我codeD:              INT DP =像素/(INT)getResources()getDisplayMetrics()密度; 但这似乎不是返回正确的答案。我做了WVGA800其屏幕分辨率为480的仿真器由800当运行模拟器,让code印刷像素和DP值,就来到了两个320。这个模拟器是240 dpi的,其比例系数是0.75。

this return the screen width in pixels (px). To convert this to dp, I coded: int dp =pixel/(int)getResources().getDisplayMetrics().density ; This does not seem to be returning correct answer. I made the emulator of WVGA800 whose screen resolution is 480 by 800. When the run the emulator and let the code print the values of pixel and dp, it came to 320 in both. This emulator is 240 dpi whose scale factor would be 0.75.

推荐答案

试试这个

    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics ();
    display.getMetrics(outMetrics);

    float density  = getResources().getDisplayMetrics().density;
    float dpHeight = outMetrics.heightPixels / density;
    float dpWidth  = outMetrics.widthPixels / density;

感谢@托马什Hubálek

Thanks @Tomáš Hubálek

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

        float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;