android - 如何在相对布局中将两个 View 居中?

标签 android alignment android-relativelayout center

任务很简单:有两个按钮和一个位于按钮上方的 TextView。所有的小部件都应该在相关布局中居中。我唯一的想法是创建第三个小部件 View 并将其用作按钮的中心轴。有任何想法吗?冗余布局不是好的解决方案。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/app_name" />

    <View
        android:id="@+id/view_axis"
        android:layout_width="1dp"
        android:layout_height="1dp"
        android:layout_below="@id/tv_progress"
        android:layout_centerInParent="true" />

    <Button
        android:id="@+id/button_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_progress"
        android:layout_toLeftOf="@id/view_axis"
        android:text="@string/start" />

    <Button
        android:id="@+id/button_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_progress"
        android:layout_toRightOf="@id/view_axis"
        android:text="@string/stop" />

</RelativeLayout>

最佳答案

如果我正确理解你想要什么,你可以将 Button 放在 LinearLayout 中并将其居中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/tv_progress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="@string/app_name" />
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_below="@id/tv_progress">
<Button
    android:id="@+id/button_start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/start" />

<Button
    android:id="@+id/button_stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stop" />
 </LinearLayout>

我不确定这是否是您所说的“冗余布局”的意思,但如果它能满足您的需求,这样做就很好。

关于android - 如何在相对布局中将两个 View 居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17530493/

相关文章:

android - 如何在 Java 端的 GridView 中正确调整 ImageView 的大小;安卓?

android - 如何编写代码使用 Android 查询来搜索通话记录的数据库?

android - 'com.b.a.b.a' 需要 'sequence' 属性 - Proguard

react-native - React Native - 两个项目 : one on the left, 一个在中心

c++ - boost库应该依赖于结构成员对齐吗?

html - Bootstrap 类 dropdown-menu dropdown-menu-right 不适用于自定义子菜单

android - 向动态 Android TextView 添加边距

android - 文本 block 和图像的定位

Android gradle - 如何远程访问 keystore

android - 为什么我的相对布局不占用整个屏幕高度