android:gravity fails on API 18+

风格不统一 提交于 2019-12-03 15:50:05
Tomty

This appears to be a known issue in API 18+:

https://code.google.com/p/android/issues/detail?id=59368 https://code.google.com/p/android/issues/detail?id=59700

The problem seems to occur when a TextView is part of a scrollable container (e.g. ListView), making the view ignore the vertical gravity for some reason (some sources suggest this has to do with the TextView being the child of a RelativeLayout, though it's been my experience that this can happen even when no such layout is involved).

A possible workaround (albeit not a particularly elegant one), would be to wrap the TextView in a LinearLayout. You can then use "layout_gravity" on the TextView to center it inside the LinearLayout, instead of relying on "gravity" (just make sure to wrap_content so the text itself is properly centered).

E.g., in your example:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignBottom="@+id/seekbar"
    android:layout_alignParentLeft="true"
    android:layout_alignTop="@+id/seekbar"
    android:layout_toLeftOf="@+id/seekbar"
    android:layout_marginLeft="@dimen/margin_tiny_double" >

    <com.package.custom.CustomTextFont
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="left"
        android:paddingRight="@dimen/margin_tiny"
        android:text="@string/text1"
        android:textColor="@color/black"
        android:textSize="@dimen/size_text_normal" />

</LinearLayout>

This method does have the disadvantage of adding an otherwise-unnecessary level to your view hierarchy, but it currently seems to be the only way around this (other than reverting to an earlier API level).

Also see similar question at: Android sdk 18 TextView gravity doesn't work vertically

Your textview height is "wrap_content", which means the height of the textview will be the same as the height of the text. If you change the background of the textview to black, it might be easier to see the bounds of the view. I'm guessing you'll find that the textview doesn't have as much height as you expect.

Try setting the height of the textview to match_parent. You can wrap the textview inside another view if needed and modify its height as appropriate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!