android - 相对布局 : align View centered horizontal or vertical relative to other view

标签 android center android-relativelayout

是否可以根据另一个已经存在的 View 在相对布局中以水平或垂直居中对齐 XML 中的 View 。

例如:假设有这样的事情:

enter image description here

第二个 TextView 应该在第一个 TextView 下方居中显示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="72dp"
        android:text="dynamic text" />

    <TextView
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:layout_marginLeft="43dp" <!-- Is there a rule to center it? -->
        android:text="centered below text 1" />

</RelativeLayout>

是否可以在 XML 中实现类似的东西?有没有我错过的规则?我不想以编程方式计算位置

最佳答案

我有一个比公认的解决方案更好的解决方案。没有额外的嵌套!您可以通过在较小的 View 上组合两个属性来做到这一点。如果您水平居中,您可以同时使用 align_start 和 align_end 到更大的 View 。确保文本重力居中 btw "android:gravity="center"。对于垂直对齐,请同时使用 align_top 和 align_bottom。下面是修改后的布局实现。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="43dp" >

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/second"
    android:layout_alignEnd="@+id/second"
    android:gravity="center"
    android:text="dynamic text" />

<TextView
    android:id="@+id/second"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/textView"
    android:gravity="center"
    android:text="centered below text 1" />

</RelativeLayout>

不需要像接受的答案那样不必要的嵌套。

关于android - 相对布局 : align View centered horizontal or vertical relative to other view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16510773/

相关文章:

html - 中心 Christmax 日历

android - 如何填充两个布局之间的剩余空间

android - 如何在相对布局中以父 View 为中心对齐下方的 View

android - 如何阻止 TextView 超出其他项relativelayout 太远?

android - ViewPager Activity 通知特定事件的 Fragment

安卓 Twitter4j 错误

android - 在加载 TileOverlay Map API v2 Android 时保持图 block 可见

java - 如何使 JButtons(主菜单)在框架中居中?

java - 重新访问 fragment 后,在 fragment 内设置文本不起作用

html - CSS 居中图 block (宽度可调)