丑陋的小虫? RelativeLayout中的第一项无法居中

时间:2013-05-24 08:50:39

标签: android layout

我们尝试一件简单的事情。在RelativeLayout中水平和垂直居中显示TextView。

这应该是

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

出乎所有人的意料,文字显示在左上角。

但是现在为整个事情添加一个毫无意义的LinearLayout:

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

    <!-- First item in a relative Layout cannot be centered  -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
         >
    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

和tadaaaa!文字出现在我们想要的地方。如果不更改TextView的位置,则无法删除LinearLayout中的任何行。似乎RelativeLayout需要一些项目与顶部/底部和右/左对齐,然后才能将任何其他项目居中。

1 个答案:

答案 0 :(得分:1)

类似的问题?

问题描述

我目前遇到一个类似的问题,即RelativeLayout包裹TextView,由于使用了android:layout_centerInParent="true"而应该居中{。}}。

在API 21级设备或模拟器上运行我的代码会显示正确居中的文本。

但是,在API级别19上运行相同的代码会将文本视图放在包装RelativeLayout的顶部而不是居中。

示例项目

为了便于遵循,我在https://github.com/hanscappelle/SO-16731025创建了一个示例项目。只需从git中查看此代码并在Android Studio中导入,您就可以运行代码。

可视化

您甚至可以使用Android Studio中的设计预览测试此问题,只需更改用于渲染的SDK版本。

只需在layout/with_scrollview.xml打开文件,您就可以在Android Studio的预览中看到它。

使用API​​级别21:

enter image description here

使用API​​级别19的相同布局:

enter image description here

解决

包装ScrollView

作为解决方法,我发现删除包装ScrollView可以解决问题。

什么没有帮助

虚拟视图

在您之间添加虚拟LinearLayout(或任何其他视图),就像您建议的那样,并没有解决我的问题。

示例项目将此技术应用于屏幕右侧的圆圈中。