我挣扎于同样的问题,并发现了很大solution。
RelativeLayout
规则,如“leftOf”或“rightOf”可以通过编程来实现这样的:
RelativeLayout container = new RelativeLayout(getApplicationContext());
Button weight = new Button(getApplicationContext());
final int WEIGHT_ID = 0;
weight.setId(WEIGHT_ID);
weight.setText("0.0");
LayoutParams wrapBoth =
new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
container.addView(weight, wrapBoth);
Button increaseWeight = new Button(getApplicationContext());
increaseWeight.setText("+");
// Note the difference: RelativeLayout.LayoutParams in spite of LayoutParams
RelativeLayout.LayoutParams toBeRightOfWeight =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
container.addView(parameter,wrapBoth);
// Sweet part
clearAirParams.addRule(RelativeLayout.RIGHT_OF, WEIGHT_ID);
container.addView(increaseWeight, toBeRightOfWeight);
所以,在代码中你可以创建一个“容器” RelativeLayout
,然后用唯一的ID添加几个View
S和,最后,创建RelativeLayout.LayoutParams
对象来实现类似于XML的类糖的方法。