我有一个由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
即使建议的解决方案有效,但它可能不是针对每种情况的最佳解决方案,因为根据ViewTreeObserver的文档。OnGlobalLayoutListener
当全局布局状态或视图树中视图的可见性发生变化时,将调用回调的接口定义。
这意味着它会被多次调用,并不总是测量视图(它的高度和宽度是确定的)
另一种方法是使用ViewTreeObserver。OnPreDrawListener只在视图准备好绘制并拥有所有测量值时被调用。
final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnPreDrawListener(new OnPreDrawListener() {
@Override
public void onPreDraw() {
tv.getViewTreeObserver().removeOnPreDrawListener(this);
// Your view will have valid height and width at this point
tv.getHeight();
tv.getWidth();
}
});
正如F.X.提到的,你可以使用OnLayoutChangeListener来跟踪你想要跟踪的视图
view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// Make changes
}
});
如果只需要初始布局,可以在回调中删除侦听器。
我相信OP早就消失了,但如果这个答案能够帮助未来的搜索者,我想我应该发布一个我发现的解决方案。我已经在onCreate()方法中添加了以下代码:
编辑:07/05/11以包括来自注释的代码:
final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)tv.getBackground();
ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
ViewTreeObserver obs = tv.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
}
});
首先,我得到一个最终引用我的TextView(访问在onGlobalLayout()方法)。接下来,我从我的TextView获得ViewTreeObserver,并添加一个OnGlobalLayoutListener,覆盖onGLobalLayout(似乎没有一个超类方法调用这里…)并添加我的代码,这需要知道视图的测量到这个侦听器。一切都如我所料,所以我希望这是能够帮助。