首页 > 解决方案 > 在竖屏模式下获取屏幕宽度

问题描述

我想在纵向模式下获得屏幕的宽度。这段代码

public static int getScreenWidth() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

给了我完整的宽度,我想要的只是用户可见的宽度(手机屏幕的宽度不是完整的分辨率)。

标签: android

解决方案


根据您的评论,问题是当您使用 定位视图时getScreenWidth(),视图不会出现。

定位视图时,会设置屏幕左边缘和视图左边缘之间的距离。请看一下这张图片:

在此处输入图像描述

下面的代码获取View对象并将其定位在右侧屏幕边缘旁边。

public void alignViewRight(View v) {
    v.setX(getScreenWidth() - v.getWidth());
}

public int getScreenWidth() {
    return Resources.getSystem().getDisplayMetrics().widthPixels;
}

推荐阅读