在Android中,要在线性布局中居中两个元素,可以使用以下方法:
示例代码:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="居中文本" />
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
android:layout_centerVertical="true"
属性将它们垂直居中对齐。示例代码:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/leftElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:text="左侧元素" />
<TextView
android:id="@+id/rightElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:text="右侧元素" />
</RelativeLayout>
以上是两种常用的方法来实现在线性布局中居中两个元素的方式。根据具体的需求和布局结构,可以选择适合的方法来实现居中对齐。
领取专属 10元无门槛券
手把手带您无忧上云