如何确定屏幕宽度DP或浸方面在运行时的Andr​​oid? [英] How to determine the screen width in terms of dp or dip at runtime in Android?

查看:127
本文介绍了如何确定屏幕宽度DP或浸方面在运行时的Andr​​oid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要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;

这篇关于如何确定屏幕宽度DP或浸方面在运行时的Andr​​oid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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