How to get a textview centred on top of an ImageView

不想你离开。 提交于 2019-12-13 00:26:03

问题


I am attempting to get some text to appear in the centre of an ImageView. But using this xml (below) what I see its the text wedged in the top left of the FrameLayout. What did I do wrong?

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="1"
  >

        <ImageView
            android:id="@+id/levbut"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:scaleType="centerInside"
            android:src="@drawable/starbut"
             />

    <TextView
        android:id="@+id/tvtest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello"
        />

</FrameLayout>

回答1:


You can either add a gravity to the FrameLayout, a layout_gravity to the textView, or change it to a RelativeLayout and add centerInParent="true".

<FrameLayout
    ...
    android:gravity="center">

or

<FrameLayout
    ... />
    <TextView
        ...
        android:layout_gravity="center" />
</FrameLayout>

or

<ReltiveLayout
    ...>
    <ImageView ... />
    <TextView
        ...
        android:layout_centerInParent="true" />
</RelativeLayout>



回答2:


Change android:layout_gravity="center" with android:gravity="center" for the FrameLayout element.




回答3:


Try this add android:gravity="center" for TextView and change its width and height to Match parent

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" >

<ImageView
    android:id="@+id/levbut"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:scaleType="centerInside"
    android:src="@drawable/star_but" />

<TextView
    android:id="@+id/tvtest"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Hello" 
    android:gravity="center"/>



来源:https://stackoverflow.com/questions/17752811/how-to-get-a-textview-centred-on-top-of-an-imageview

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