我想获得设置为包装内容的线性布局的高度。但它是零。 我试试这个代码:
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
ViewTreeObserver vto = below.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
width = below.getMeasuredWidth();
height = below.getMeasuredHeight();
}
});
和:
LinearLayout below= (LinearLayout) findViewById(R.id.below);
final int belowh=below.getHeight();
使用代码:
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
ViewTreeObserver vto = below.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if(below.getMeasuredHeight()> 0){
this.below.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = below.getMeasuredWidth();
int height = below.getMeasuredHeight();
}
}
})
;
答案 0 :(得分:3)
尝试使用此代码在创建视图后获取布局宽度和高度
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
below.post(new Runnable()
{
@Override
public void run()
{
Log.i("TAG", "Layout width :"+ below.getWidth());
Log.i("TAG", "Layout height :"+ below.getHeight());
}
});
希望这个帮助
答案 1 :(得分:0)
试试这个
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
ViewTreeObserver vto = below.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if(below.getMeasuredHeight()> 0){
this.below.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = below.getMeasuredWidth();
int height = below.getMeasuredHeight();
}
}
})
;
答案 2 :(得分:0)
@coder android
如果你还在堆叠......请看这个。我认为这将完美无缺。
找到以下代码How to retrieve the dimensions of a view?
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);
}
}
});