我掙扎於同樣的問題,並發現了很大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的類糖的方法。