如何在Android运行时确定屏幕宽度(dp或dip)?

发布于 2024-11-17 03:13:53 字数 403 浏览 7 评论 0原文

我需要使用dip/dp(在java文件中)对android小部件的布局进行编码。在运行时,如果我编码,

int Pixel=this.getWindowManager().getDefaultDisplay().getWidth();

这将返回屏幕宽度(以像素 (px) 为单位)。为了将其转换为 dp,我编码:

int dp =pixel/(int)getResources().getDisplayMetrics().密度;

这似乎没有返回正确的答案。我制作了WVGA800的模拟器,其屏幕分辨率为480 x 800。当运行模拟器并让代码打印像素和dp的值时,两者都达到了320。该模拟器的分辨率为 240 dpi,其比例因子为 0.75。

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();

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

等待圉鍢 2024-11-24 03:13:54

用科特林语回答:

  context?.let {
        val displayMetrics = it.resources.displayMetrics
        val dpHeight = displayMetrics.heightPixels / displayMetrics.density
        val dpWidth = displayMetrics.widthPixels / displayMetrics.density
    }

Answer in kotlin:

  context?.let {
        val displayMetrics = it.resources.displayMetrics
        val dpHeight = displayMetrics.heightPixels / displayMetrics.density
        val dpWidth = displayMetrics.widthPixels / displayMetrics.density
    }
夏日落 2024-11-24 03:13:54

在单行 Compose 的新世界中

val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }

In the new world of Compose on one line

val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }
情域 2024-11-24 03:13:54

通过一些良好的装饰以 DP 形式获取屏幕宽度和高度:

步骤 1:创建接口

public interface ScreenInterface {

   float getWidth();

   float getHeight();

}

步骤 2:创建实现类

public class Screen implements ScreenInterface {
    private Activity activity;

    public Screen(Activity activity) {
        this.activity = activity;
    }

    private DisplayMetrics getScreenDimension(Activity activity) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    private float getScreenDensity(Activity activity) {
        return activity.getResources().getDisplayMetrics().density;
    }

    @Override
    public float getWidth() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.widthPixels / getScreenDensity(activity);
    }

    @Override
    public float getHeight() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.heightPixels / getScreenDensity(activity);
    }
} 

步骤 3:获取活动中的宽度和高度:

Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();

Get Screen Width and Height in terms of DP with some good decoration:

Step 1: Create interface

public interface ScreenInterface {

   float getWidth();

   float getHeight();

}

Step 2: Create implementer class

public class Screen implements ScreenInterface {
    private Activity activity;

    public Screen(Activity activity) {
        this.activity = activity;
    }

    private DisplayMetrics getScreenDimension(Activity activity) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    private float getScreenDensity(Activity activity) {
        return activity.getResources().getDisplayMetrics().density;
    }

    @Override
    public float getWidth() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.widthPixels / getScreenDensity(activity);
    }

    @Override
    public float getHeight() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.heightPixels / getScreenDensity(activity);
    }
} 

Step 3: Get width and height in activity:

Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();
Spring初心 2024-11-24 03:13:54

这是基于先前响应使用的复制/粘贴功能。

  /**
     * @param context
     * @return the Screen height in DP
     */
    public static float getHeightDp(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
        return dpHeight;
    }

    /**
     * @param context
     * @return the screnn width in dp
     */
    public static float getWidthDp(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
        return dpWidth;
    }

This is a copy/pastable function to be used based on the previous responses.

  /**
     * @param context
     * @return the Screen height in DP
     */
    public static float getHeightDp(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
        return dpHeight;
    }

    /**
     * @param context
     * @return the screnn width in dp
     */
    public static float getWidthDp(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
        return dpWidth;
    }
把回忆走一遍 2024-11-24 03:13:54

如果您只想了解屏幕宽度,只需在开发者选项中搜索“最小屏幕宽度”即可。您甚至可以编辑它。

If you just want to know about your screen width, you can just search for "smallest screen width" in your developer options. You can even edit it.

听,心雨的声音 2024-11-24 03:13:54

val screenSize = size.toDpSize()

val screenSize = size.toDpSize()

红衣飘飘貌似仙 2024-11-24 03:13:54

您的问题是将浮点数转换为 int,从而失去精度。您还应该乘以该因子,而不是除以。

这样做:

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

Your problem is with casting the float to an int, losing precision. You should also multiply with the factor and not divide.

Do this:

int dp = (int)(pixel*getResources().getDisplayMetrics().density);
网白 2024-11-24 03:13:53

正如 @Tomáš Hubálek 提到的;
尝试类似:

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

尝试旧答案:

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;

As @Tomáš Hubálek mentioned;
Try something like:

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

OR

Try old answer:

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;
ˉ厌 2024-11-24 03:13:53

我从 Google 偶然发现了这个问题,后来我发现了一个适用于 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 所指出的,这将返回屏幕的可用宽度/高度(这应该是大多数情况下有趣的宽度/高度)用途)。如果您需要实际显示尺寸,请坚持最上面的答案。

I stumbled upon this question from Google, and later on I found an easy solution valid for API >= 13.

For future references:

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.

See Configuration class reference

Edit: As noted by Nick Baicoianu, this returns the usable width/height of the screen (which should be the interesting ones in most uses). If you need the actual display dimensions stick to the top answer.

落花浅忆 2024-11-24 03:13:53

2023 年 Kotlin 的答案已简化:

val widthDp = resources.displayMetrics.run { widthPixels / density }
val heightDp = resources.displayMetrics.run { heightPixels / density }

简单来说:

val (height, width) = resources.displayMetrics.run { heightPixels/density to widthPixels/density }

对于 Jetpack Compose:

val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }

2023 Answer simplified for Kotlin:

val widthDp = resources.displayMetrics.run { widthPixels / density }
val heightDp = resources.displayMetrics.run { heightPixels / density }

As one-liner:

val (height, width) = resources.displayMetrics.run { heightPixels/density to widthPixels/density }

For Jetpack Compose:

val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }
林空鹿饮溪 2024-11-24 03:13:53

用这个代替怎么样?

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

How about using this instead ?

final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels/displayMetrics.density;
final float screenHeightInDp=displayMetrics.heightPixels/displayMetrics.density;
晚雾 2024-11-24 03:13:53

您缺少默认密度值 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 设备上屏幕的一半(我认为平板电脑除外)

You are missing default density value of 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

In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)

沫尐诺 2024-11-24 03:13:53
DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;

int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;

int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;


int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;
DisplayMetrics displayMetrics = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;

int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;

int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;


int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文