问题
I have a vertical layout that contains 10 relative layouts. The UX team has prepared a background with horizontal lines so I have to fit the 10 relative layout elements dynamically on the screen. I have wrote the following code to set a listener to get the vertical layout height and then to do the calculations. The problem is I get height value of -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);
}
}
}
});
来源:https://stackoverflow.com/questions/20593095/set-layout-margins-dynamically