我需要使用dip/dp(在java文件中)编码android小部件的布局。在运行时,如果我编码, .getWidth .getDefaultDisplay int像素= this.getWindowManager () () ();

返回屏幕宽度(像素)。为了将其转换为dp,我编写了如下代码: int dp =pixel/(int)getResources().getDisplayMetrics().density; 这似乎没有返回正确的答案。我做了WVGA800的模拟器,屏幕分辨率是480 * 800。当运行模拟器并让代码打印像素和dp值时,两者都是320。该模拟器为240 dpi,比例因子为0.75。


当前回答

如果你只是想知道你的屏幕宽度,你可以在你的开发者选项中搜索“最小屏幕宽度”。你甚至可以编辑它。

其他回答

如果你只是想知道你的屏幕宽度,你可以在你的开发者选项中搜索“最小屏幕宽度”。你甚至可以编辑它。

您缺少默认密度值160。

    2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
    1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
    3 px = 2 dip if dpi == 240(hdpi), 840x480 screen

换句话说,如果你在纵向模式下设计宽度为160dip的布局,它将在所有ldpi/mdpi/hdpi设备上占屏幕的一半(我认为平板电脑除外)

用这个代替怎么样?

final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels/displayMetrics.density;
final float screenHeightInDp=displayMetrics.heightPixels/displayMetrics.density;

你的问题是将浮点型转换为int型,失去精度。你还应该与因子相乘,而不是除。

这样做:

int dp = (int)(pixel*getResources().getDisplayMetrics().density);

我从谷歌中偶然发现了这个问题,后来我找到了一个适用于API >= 13的简单解决方案。

供日后参考:

Configuration configuration = yourActivity.getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.

参见配置类参考

编辑:正如Nick Baicoianu所指出的,这将返回屏幕的可用宽度/高度(这应该是大多数使用中有趣的部分)。如果您需要实际的显示尺寸,请坚持顶部的答案。