文本在texview中的垂直居中不工作



我确信这已经回答了之前,但我已经无情地搜索,无法找到一个答案,解决我的确切问题,这是:

我有一个TextView在ImageView的顶部设置如下:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
    android:id="@+id/imageForCustomAdapter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_ball_3" />
<TextView
    android:id="@+id/textOnBall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="1dp"
    android:textColor="#000000"
    android:textSize="50dp"
    android:hint="10"
    android:layout_alignParentBottom="false"
    android:layout_centerInParent="true"
    android:layout_alignTop="@+id/imageForCustomAdapter"
    android:layout_alignLeft="@+id/imageForCustomAdapter"
    android:layout_alignBottom="@+id/imageForCustomAdapter"
    android:layout_alignRight="@+id/imageForCustomAdapter"
    android:gravity="center" />
</RelativeLayout>

TextView与ImageView对齐,使其大小相同,我希望文本在水平和垂直方向都居中。

Android Studio中的渲染显示它被正确居中但当我在实际设备上运行这个应用时,文本只水平居中。我已经尝试了android:gravity=的所有不同组合,但没有任何工作。

我做错了什么?

我首先要说,我真的不喜欢RelativeLayout,这里有一个很好的例子。它功能强大,但也可能令人严重困惑,简单性很重要。

你有许多布局指令,它们很容易相互冲突。试试这样写:

<FrameLayout
android:layout_width="wrap_content"
    android:layout_height="wrap_content"
>
<ImageView
    android:id="@+id/imageForCustomAdapter"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_ball_3" />
<TextView
    android:id="@+id/textOnBall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#000000"
    android:textSize="50dp"
    android:hint="10"
    android:layout_gravity="center" />
</FrameLayout>
顺便说一句,'wrap_content'在framayout上很重要。假设ImageView总是比TextView大,它会驱动父高度。如果TextView可能更大,请确保ImageView也居中。

为什么它在工作室工作而不是在现实生活中,不知道。

最新更新