这是我的布局文件:
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/imageLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center"
android:background="@color/silver">
<TextView
android:id="@+id/bottom"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignBaseline="@id/imageLayout"
android:layout_alignBottom="@id/imageLayout"
android:background="@color/red"
android:gravity="center"
android:textColor="@color/white"
android:textSize="30sp"
/>
<TextView
android:id="@+id/above"
android:layout_width="match_parent"
android:layout_height="50dp"
android:paddingBottom="3dp"
android:layout_above="@id/bottom"
android:background="@color/blue"
android:gravity="center"
android:textColor="@color/white"
android:textSize="30sp"
</RelativeLayout>
我将ImageViews动态添加到名为MatchGame.xml的about布局中使用以下代码
RelativeLayout re = (RelativeLayout)findViewById(R.id.imageLayout);
re.setGravity(Gravity.CENTER);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
final ImageView img = new ImageView(this);
//do some operations with image
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(40,40);
if (j == 0) {
// rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT,
// RelativeLayout.TRUE);
}
else {
rlp.addRule(RelativeLayout.RIGHT_OF, index - 1);
}
if (i == 0) {
// rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP,
// RelativeLayout.TRUE);
}
else {
rlp.addRule(RelativeLayout.BELOW, index - cols);
}
img.setLayoutParams(rlp);
re.addView(img);
}
}
图像以矩阵的形式添加,但视图对齐到屏幕的左侧,但我希望矩阵位于屏幕的中心。
答案 0 :(得分:0)
正如我所说,你可以将图像矩阵包装在另一个RelativeLayout
中,并将其置于最初的RelativeLayout
中:
RelativeLayout re = (RelativeLayout)findViewById(R.id.imageLayout);
RelativeLayout content = new RelativeLayout(this);
RelativeLayout.LayoutParams clp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
clp.addRule(RelativeLayout.CENTER_IN_PARENT);
content.setLayoutParams(clp);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// ...the current loop...
img.setLayoutParams(rlp);
content.addView(img);
}
}
re.addView(content);
同时从xml android:gravity
中移除android:layout_gravity
和RelativeLayout
属性。