是否可以根据另一个已经存在的 View 在相对布局中以水平或垂直居中对齐 XML 中的 View 。
例如:假设有这样的事情:
第二个 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/