soc*_*qwe 17 android center android-relativelayout
是否可以根据另一个已存在的视图将相对于中心水平或垂直的RelativeLayout中的视图对齐.
例如:假设有这样的事情:

第二个文本视图应显示在第一个文本视图下方的中心:
<?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>
Run Code Online (Sandbox Code Playgroud)
有可能在XML中实现类似的东西吗?有没有我错过的规则?我不想以编程方式计算位置
Jes*_*rdo 29
我有一个比接受的更好的解决方案.没有额外的巢!您可以通过在较小视图上组合两个属性来完成此操作.如果您水平居中,则可以将align_start和align_end用于更大的视图.确保文本重力位于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>
Run Code Online (Sandbox Code Playgroud)
不需要像接受的答案那样不必要的嵌套.
Nou*_*eep 13
为这些视图使用单独的父布局并将其添加到主布局中(如果有,可以包含其他内容)
<?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" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:layout_marginLeft = "30dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dynamic text" />
<TextView
android:id="@+id/second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="centered below text 1" />
</LinearLayout>
...
...
other veiws go here
...
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
使用适合您的以下内容
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32906 次 |
| 最近记录: |