无法弄清楚如何获得视图/布局宽/高 [英] Can't figure out how to get view/layout width/height

查看:120
本文介绍了无法弄清楚如何获得视图/布局宽/高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Android新手。这应该是最容易的事在世界上,但计算出来是推动我疯狂:如何获得一个视图或布局的尺寸

标准的做法似乎是沿着线的东西:

((的LinearLayout)this.findViewById(R.id.MyLayout))的getWidth();

除了这总是返回零,因为我试图做到这一点,当活动开始了(的onCreate)和几何尚未设定。我试图把在睡觉,给它一个机会,建立布局,不同的是它的不会的设置,直到返回的onCreate布局。因此,它显然不是线程。 :P

我发现了一堆谈论覆盖各种不同的回调函数,以确保当你调用的getWidth布局加载页面 - 但它们都扔了错误,当我试图把覆盖在我的活动。因此,我可以假设,他们是被测量回调的布局和/或意见。这问题是,我没有使用自定义视图/布局类 - 只是标准的。所以,我不能只是添加替代,据我所知。

任何人都知道我应该怎么办?我花了大约8小时这个问题,并得到行不通的。而且它的东西,就是通常这样的琐碎的事情在大多数开发环境!

解决方案

 最终视图中查看= .....; //你的看法

view.getViewTreeObserver()。addOnGlobalLayoutListener(
    新ViewTreeObserver.OnGlobalLayoutListener(){

      @覆盖
      公共无效onGlobalLayout(){
        //确保它不叫了
        。view.getViewTreeObserver()removeGlobalOnLayoutListener(本);

        //你的code到这里的观点尺寸:
        // ...
      }
    });
 

I'm an Android newbie. This should be the easiest thing in the world, but figuring it out is driving me batty: how do I get the dimensions of a view or layout?

The standard approach seems to be something along the lines of:

((LinearLayout)this.findViewById(R.id.MyLayout)).getWidth();

Except that this always returns zero, since I'm trying to do this when the Activity starts up (onCreate) and the geometry isn't set yet. I tried putting in sleeps to give it a chance to set up the layout, except that it won't set up the layout until onCreate returns. So it's clearly not threaded. :P

I found a bunch of pages talking about overriding all sorts of different callback functions in order to be sure that the layout is loaded when you call getWidth -- but all of them threw errors when I tried to put the overrides in my Activity. So I can assume that they were callbacks for the layouts and/or views being measured. The problem with that is that I'm not using custom view/layout classes -- just the standard ones. So I can't just add an override, as far as I know.

Anyone know what I should do? I've spent something like 8 hours on this problem and gotten nowhere. And it's something that's normally such a trivial thing to do in most development environments!

解决方案

final View view = .....; // your view

view.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {

      @Override
      public void onGlobalLayout() {
        // make sure it is not called anymore 
        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        // your code to get dimensions of the view here:
        // ...
      }
    });

这篇关于无法弄清楚如何获得视图/布局宽/高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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