【问题标题】:How Get width of a view using getWidth()?如何使用 getWidth() 获取视图的宽度?
【发布时间】:2019-08-27 09:27:07
【问题描述】:

如何在 Android 中获取视图的宽度或高度? 当使用 getWidth() getHeight() 方法时,它们返回 0

另一个子问题是 getWidth() 以 dp 或 px 为单位的返回值 ..

【问题讨论】:

标签: java android


【解决方案1】:

您的视图尚未渲染。你必须等待它!

使用 post 方法。

yourView.post(new Runnable() {
        @Override
        public void run() {
            int height = yourView.getHeight();
            int width = yourView.getWidth();
        }
    });

高度和宽度值将采用像素格式

如果你得到这个异常:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

将您的 .post() 代码放入 runOnUiThread 方法中。

【讨论】:

    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多