如果你想为中心的ImageButtons
等间隔左右,那么你可以简单的将它们包装在一个LinearLayout
,然后居中,在父RelativeLayout
LinearLayout
:
RelativeLayout rlLayout = (RelativeLayout) findViewById(R.id.parent);
LinearLayout container = new LinearLayout(this);
for (int i = 0; i < 5; i++) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ImageButton ib = new ImageButton(this);
ib.setId(i);
ib.setLayoutParams(layoutParams);
ib.setBackgroundResource(R.drawable.ic_launcher);
container.addView(ib);
if (ib.getId() == position) {
ib.setBackgroundResource(R.drawable.black_circle_32x32);
}
}
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL,
RelativeLayout.TRUE);
rlLayout.addView(container, layoutParams);
如果你想写更多的代码只是做上述那么你可以修改当前的布局,并添加这个元素作为锚:
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerHorizontal="true"
android:id="@+id/anchor" />
,然后在代码中的位置ImageButtons
这种定位的View
的左,右:
int anchorId = R.id.anchor;
int btnsNr = 6; // this is the number of Buttons
RelativeLayout rlLayout = (RelativeLayout) findViewById(R.id.parent);
if (btnsNr % 2 != 0) {
anchorId = 1000;
btnsNr--;
ImageButton imgb = new ImageButton(this);
imgb.setImageResource(R.drawable.shop_open);
imgb.setId(anchorId);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rlp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
rlLayout.addView(imgb, rlp);
}
int whichPart = 1;
while (whichPart >= 0) {
int previousId = anchorId;
for (int i = 0; i < (btnsNr/2); i++) {
RelativeLayout.LayoutParams tmp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if (whichPart == 1) {
tmp.addRule(RelativeLayout.LEFT_OF, previousId);
} else {
tmp.addRule(RelativeLayout.RIGHT_OF, previousId);
}
ImageButton imgb = new ImageButton(this);
previousId += whichPart == 1 ? -1 : 1;
imgb.setId(previousId);
imgb.setImageResource(R.drawable.shop_open);
rlLayout.addView(imgb, tmp);
}
whichPart--;
}
如果你想计算的ImageButtons
适合屏幕的数量(和水平居中他们),你应该提到。
我使用了一个相对布局(从儿童到父母的相对布局),包含高度和宽度的内容,将它对齐到中心位置并将按钮添加到它。我认为没有必要添加视图容器。我通过指定边距动态地添加按钮。它为我工作。谢谢你的帮助!!! – krisDrOid
@krisDrOid添加“视图”是另一种方式(使用更多的代码)。我使用了一个'LinearLayout',但当然你可以像你一样使用'RelativeLayout'。 – Luksprog