You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Relative Layout:如何将视图置于另一视图中心?

在RelativeLayout中让视图居中于另一视图的方法

不用手动调边距,有两种精准又省事的实现方式:

方法一:用RelativeLayout的原生属性组合

直接给需要居中的视图设置两个属性,让它的水平、垂直中心分别和目标视图对齐:

  • android:layout_centerHorizontal="@id/目标视图ID":让当前视图的水平中心和目标视图的水平中心重合
  • android:layout_centerVertical="@id/目标视图ID":让当前视图的垂直中心和目标视图的垂直中心重合

举个XML代码例子:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 被作为参照的目标视图 -->
    <View
        android:id="@+id/target_view"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#ff4444"/>

    <!-- 需要居中的视图 -->
    <View
        android:id="@+id/centered_view"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="#44ff44"
        android:layout_centerHorizontal="@id/target_view"
        android:layout_centerVertical="@id/target_view"/>
</RelativeLayout>

方法二:改用ConstraintLayout(更推荐)

如果你的项目已经用了AndroidX或者Material组件,建议直接用ConstraintLayout替代RelativeLayout——它的布局能力更强,实现居中更直观:
给需要居中的视图设置四个约束,让它的上下左右都和目标视图对齐,默认就会居中显示:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/target_view"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#ff4444"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <View
        android:id="@+id/centered_view"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="#44ff44"
        app:layout_constraintStart_toStartOf="@id/target_view"
        app:layout_constraintEnd_toEndOf="@id/target_view"
        app:layout_constraintTop_toTopOf="@id/target_view"
        app:layout_constraintBottom_toBottomOf="@id/target_view"/>
</androidx.constraintlayout.widget.ConstraintLayout>

内容的提问来源于stack exchange,提问作者Matin Baki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:04:58