如何以编程方式将垂直 LinearLayout layout_gravity 设置为 center_horizontal? (Xamarin.Android)

How to set vertical LinearLayout layout_gravity to center_horizontal programatically? (Xamarin.Android)

我想以编程方式将以下 LinearLayout 居中到他的 parent 的中心:

<LinearLayout
    android:id="@+id/SignButtonsLinearLayout"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <homes.shared.components.customviews.HomesButton
        android:id="@+id/CheckListPDFClosureButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="3dip"
        android:drawableLeft="@drawable/CheckListPDFClosure"
        android:background="@drawable/MainBlueButton"
        style="@style/WhiteDeliveryNoteMenuBold"
        android:text="@string/CheckListPDFClosure" />
   <homes.shared.components.customviews.HomesButton
        android:id="@+id/SignatureAndCloseButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/SignatureAndClosure"
        android:background="@drawable/MainBlueButton"
        style="@style/WhiteDeliveryNoteMenuBold"
        android:text="@string/SignatureAndClose" /> 
</LinearLayout> 

我在这样的代码中实例化了 LinearLayout

LinearLayout ll = this.FindViewById<LinearLayout>(Resource.Id.SignButtonsLinearLayout);

但是 object 没有 LayoutGravity 属性

你可以像这样快速完成:

LinearLayout ll = this.FindViewById<LinearLayout>(Resource.Id.SignButtonsLinearLayout);
ll.SetGravity(GravityFlags.Center);

或者你也可以这样做:

LinearLayout ll = this.FindViewById<LinearLayout>(Resource.Id.SignButtonsLinearLayout);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)lin.LayoutParameters;
layoutParams.Gravity = GravityFlags.Center;
ll.LayoutParameters = layoutParams;

更多信息可以在这里找到 SO reply here as well.

编辑:

抱歉,要调整设置视图或布局相对于其父级的重力的布局重力,那么您应该能够将此属性添加到您的 axml 布局文件中。 android:layout_gravity="center" 像这样:

<LinearLayout
    android:id="@+id/SignButtonsLinearLayout"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

另一种选择是堆叠布局,因此您可以将线性布局包裹在这样的相对布局中,并在父级中使用居中。

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:focusableInTouchMode="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <LinearLayout
        android:id="@+id/SignButtonsLinearLayout"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </LinearLayout>
</RelativeLayout>