如何在Android中居文字?

时间:2014-07-11 15:31:02

标签: java android xml text center

我已阅读所有可能的解决方案,但仍无法解决此问题:

这是我的代码:

    <TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@string/your_total"
    android:textSize="45sp" />

    <Button
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:layout_gravity="fill"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="26dp"
    android:text="@string/add"
    android:textSize="20sp" />

我希望文本居中,但只有从中心 - you can see it here开始,在textView和按钮中都是如此。 谢谢!

3 个答案:

答案 0 :(得分:0)

尝试使用此

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:text="@string/your_total"
android:textSize="45sp" />

而不是

<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/your_total"
android:textSize="45sp" />

答案 1 :(得分:0)

我已在LinearLayoutRelativeLayout内对您的文字视图进行了测试,文字居中:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="MENSAGEM DE TESTE"
            android:textSize="18sp" />

我假设您的问题是主要布局,特别是 android:layout_width 应该是match_parent

答案 2 :(得分:0)

感谢大家的帮助,最终在another topic中找到了答案:重启Eclipse。 我认为它以某种方式连接到API版本(我使用20)。