当Android计算视图的宽度和高度时 [英] When android calculate width and height of views

查看:59
本文介绍了当Android计算视图的宽度和高度时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过代码创建视图层次结构,然后在活动"中使用像参数一样的根视图进行 setContentView().

I create my hierarchy of views by code, and then I do setContentView()in the Activity with my root view like argument.

我需要在运行时知道一个视图的宽度和高度,但是如果我执行 getWidth() getHeight(),我将得到0.如果我等待几秒钟我得到正确的宽度或高度.

I need know width and height of one view in runtime but if i do getWidth() or getHeight(), i get 0. If i wait a few seconds i get the correct width or height.

我只想知道android在什么时候计算视图的宽度/高度.我的代码不是很出色

I only want to know in what moment android calculate width / height of views. My code isn't outstanding

谢谢!

推荐答案

这是因为尚未在 onCreate()中计算布局.因此,您需要添加 GlobalLayoutListener 来了解何时已计算布局并将其放置在屏幕中.

This is because in onCreate() the layouts haven't been calculated yet. So you need to add a GlobalLayoutListener to know when layouts has been calculated and placed in screen.

final View view = findViewById(R.id.root);
ViewTreeObserver vto = view.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewTreeObserver vto = view.getViewTreeObserver();
                    vto.removeGlobalOnLayoutListener(this);
                }
            });

其中root是根布局(即LinearLayout,RelativeLayout).用@ + id/root分配您的根布局.

Where root is the root layout (LinearLayout, RelativeLayout i.e). Assign your root layout with the @+id/root.

这篇关于当Android计算视图的宽度和高度时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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