我有一个由tableelayout, TableRow和TextView组成的视图。我想让它看起来像一个网格。我需要得到这个网格的高度和宽度。方法getHeight()和getWidth()总是返回0。当我动态格式化网格和使用XML版本时,就会发生这种情况。

如何检索视图的维度?


下面是我在调试中用来检查结果的测试程序:

import android.app.Activity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TextView;

public class appwig extends Activity {  
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.maindemo);  //<- includes the grid called "board"
      int vh = 0;   
      int vw = 0;

      //Test-1 used the xml layout (which is displayed on the screen):
      TableLayout tl = (TableLayout) findViewById(R.id.board);  
      tl = (TableLayout) findViewById(R.id.board);
      vh = tl.getHeight();     //<- getHeight returned 0, Why?  
      vw = tl.getWidth();     //<- getWidth returned 0, Why?   

      //Test-2 used a simple dynamically generated view:        
      TextView tv = new TextView(this);
      tv.setHeight(20);
      tv.setWidth(20);
      vh = tv.getHeight();    //<- getHeight returned 0, Why?       
      vw = tv.getWidth();    //<- getWidth returned 0, Why?

    } //eof method
} //eof class

当前回答

你应该查看视图生命周期:http://developer.android.com/reference/android/view/View.html通常你不应该知道宽度和高度,直到你的活动进入onResume状态。

其他回答

我猜这就是你需要看的:使用视图的onSizeChanged()。下面是一个关于如何使用onSizeChanged()来动态获取布局或视图的高度和宽度的扩展代码片段http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html

你应该查看视图生命周期:http://developer.android.com/reference/android/view/View.html通常你不应该知道宽度和高度,直到你的活动进入onResume状态。

更正: 我发现上面的解决方案很糟糕。尤其是当你的手机很慢的时候。 在这里,我找到了另一个解决方案: 计算出元素的px值,包括边距和边距: Dp到px: https://stackoverflow.com/a/6327095/1982712

或者dimensions .xml到px: https://stackoverflow.com/a/16276351/1982712

Sp对px: https://stackoverflow.com/a/9219417/1982712(反向解决方案)

或者尺寸到px: https://stackoverflow.com/a/16276351/1982712

就是这样。

您是否试图在构造函数中获取大小,或在获得实际图片之前运行的任何其他方法?

在所有组件实际测量之前,你不会得到任何尺寸(因为你的xml不知道你的显示大小,父节点位置等等)

尝试在onSizeChanged()之后获取值(尽管它可以用零调用),或者只是简单地等待,当你得到一个实际的图像。

我只是添加一个替代解决方案,覆盖你的活动的onWindowFocusChanged方法,你将能够得到getHeight()的值,getWidth()从那里。

@Override
public void onWindowFocusChanged (boolean hasFocus) {
        // the height will be set at this point
        int height = myEverySoTallView.getMeasuredHeight(); 
}