我们尝试一件简单的事情。在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需要一些项目与顶部/底部和右/左对齐,然后才能将任何其他项目居中。
答案 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:
使用API级别19的相同布局:
作为解决方法,我发现删除包装ScrollView可以解决问题。
在您之间添加虚拟LinearLayout
(或任何其他视图),就像您建议的那样,并没有解决我的问题。
示例项目将此技术应用于屏幕右侧的圆圈中。