我已经定义了一个自定义的相对布局,以在我的布局中强制使用方形 View 。但是我无法将 child 置于该相对布局的中心。
我的自定义 RelativeLayout 定义如下:
public class SquareView extends RelativeLayout {
public SquareView(Context context) {
super(context);
}
public SquareView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int size;
size = Math.min(widthSize, heightSize);
setMeasuredDimension(size, size);
int finalMeasureSpec = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(finalMeasureSpec, finalMeasureSpec);
}
}
我的xml如下:
<com.mypackage.SquareView
android:id="@+id/gameboard_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:padding="0dp" >
<LinearLayout
android:id="@+id/gameboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="@drawable/xmlgameboard"
android:gravity="center_horizontal"
android:orientation="vertical" >
</LinearLayout>
</com.mypackage.SquareView>
当我在图形 View 中查看 xml 文件时,我看到 SquareView (gameboard_container) 填充了所有可用空间(不是方形),但子 LinearLayout(游戏板)是方形的。
但是,子 LinearLayout(游戏板)也是左对齐的,因为我要求它居中。
我该如何解决这个问题?
谢谢。
最佳答案
经过 3 天的努力,我设法解决了这个问题。解决方案是简单地将我的 SquareView 嵌套在框架布局中。然后我可以使用
将 SquareView 居中android:layout_gravity="center_horizontal"
关于android - 在自定义 RelativeLayout 中居中子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25516594/