问题:在代码中动态获取某个控件的宽或者高,如果仅仅是在代码中通过getHeight()或者getWidth(),得到的值是0;
解决:通过ViewTreeObserver的addOnGlobalLayoutListener()监听中获取宽或者高
ViewTreeObserver vto = ll_dtk.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ll_dtk.getViewTreeObserver().removeGlobalOnLayoutListener(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ll_first.getLayoutParams());
if (isFirst) {
lp.setMargins(0, 0, 0, ll_dtk.getHeight()*2);
}else{
lp.setMargins(0, 0, 0, ll_dtk.getHeight());
}
ll_first.setLayoutParams(lp);
}
});
网友评论