RelativeLayout 垂直居中无法正常工作

RelativeLayout vertical center not working correctly

应该是一个简单的问题...但是我无法解决!这是一个简单的布局,旨在显示一个说明 header 的图标,文本比图标略高。目的是使图标与文本垂直居中,但由于某种原因,无论文本/图标大小如何,图标都比应有的像素高几个像素。 (图标是可绘制的矢量,以防万一。)

布局

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp">

    <ImageView
        android:id="@+id/icon_readings_raw"
        android:src="@drawable/ic_equals"
        android:tint="@color/colorPrimary"
        android:layout_width="14dp"
        android:layout_height="14dp"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginEnd="7dp"/>

    <TextView
        android:text="Raw sensor readings"
        android:textAllCaps="true"
        android:textColor="@color/colorPrimary"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/icon_readings_raw"/>

</RelativeLayout>

结果

问题

如何使图标与文本居中?不要求 hacky 解决方案和魔术数字,请告诉我为什么 android:layout_centerVertical="true" 没有按预期工作。

编辑#1

在@AntonMakov 的带领下,我发现了一条小路,我得出的结论是,这可能归结为 sub-pixel 渲染优化和预览 window 的性质。我的预览设置为 Nexus 5X & API27。使用 ?android:attr/textAppearanceSmall TextView 呈现为恰好 19sp;玩图标高度我注意到当它设置为 {19,13,9,7,3}sp 时,图标呈现为垂直居中。当从 19sp 中减去这些数字时,我们得到 {0,6,10,12,16}sp... 始终是偶数。这是有道理的,因为只有这样你才能获得等量的屏幕顶部和底部。

我还不明白的是,为什么不是所有甚至增量都产生正确的结果(例如 TextView 设置为 19spImageView 设置为 15sp,增量为 4)。此外,"right" 组合取决于所选设备(Nexus 6 的行为略有不同),并且在模拟器中显示时看起来也略有不同。

现在怎么办? 我们应该相信 Android OS 在实际设备上做 The Right Thing 吗?是不是只有预览才是罪魁祸首——far-from-precise 对真实事物的近似,其计算不必太认真?

通过查看您的图标,我认为它从各个方面都有一些填充。因此,即使您将它垂直居中放置,提供给图标的填充也会干扰与文本视图的对齐。

如果您从底部填充 TextView 可能会起作用,但这将是一个依赖于设备的解决方案。所以我就不推荐了。

我会建议您重新设计图标,不要在所有方面进行任何填充。

您可以将以下属性设置为 ImageView 以垂直居中图像视图

<TextView
    android:id="@+id/text"
    android:text="Raw sensor readings"
    android:textAllCaps="true"
    android:textColor="@color/black"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:layout_width="wrap_content"
    android:layout_centerVertical="true"
    android:layout_height="wrap_content"
    android:layout_toEndOf="@+id/icon_readings_raw"/>

<ImageView
    android:id="@+id/icon_readings_raw"
    android:src="@drawable/ic_launcher"
    android:tint="@color/white"
    android:layout_width="14dp"
    android:layout_height="14dp"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:layout_alignBaseline="@+id/text"
    android:layout_marginEnd="7dp"/>

经过进一步测试,明显错位的原因似乎在预览 window 而不是 Android 本身。我注意到当它们的大小差异为偶数时,图标显示与 RelativeLayout 正确对齐(例如,text/layout 的高度为 19sp,图标为 13sp相差 6sp)。更重要的是,即使图标看起来与 RelativeLayout 的中心不对齐,它在实际设备上看起来也不错。

故事的寓意:不要相信 Android Studio 中的预览 window!当它确实近距离显示出一些奇怪的东西时,您可以期待看起来略有不同的布局,在浪费太多时间追逐阴影之前仔细检查实际设备!事实证明,它被称为 preview window(而不是 HiDef Pixel-Perfect Simulator)是有原因的。