我有一个包含10个相对布局的垂直布局。 UX团队准备了一个水平线背景,所以我必须在屏幕上动态调整10个相对布局元素。 我编写了以下代码来设置一个监听器来获取垂直布局高度,然后进行计算。问题是我的高度值为-2。
final LinearLayout layout = (LinearLayout) findViewById(R.id.fav_layout);
final Context context = this;
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)layout.getLayoutParams();
int height = params.height;
if (height <= 0)
Toast.makeText(context, "measure < 0", Toast.LENGTH_SHORT).show();
else {
int count = layout.getChildCount();
for (int i=0; i<count; i++){
RelativeLayout l = (RelativeLayout) layout.getChildAt(i);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(10, height/10, 0, 0);
l.setLayoutParams(lp);
}
}
}
});