Android按钮在setText后失去文本对齐

3
我正在使用XML来绘制一个旋转的进度指示器,并附带一些文本。在屏幕底部,我有一个TableLayout,其中包含两个按钮,这些按钮都居中于页面,并且每个文本也居中。
<RelativeLayout
        android:id="@+id/progresscontainer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_horizontal">


        <ProgressBar android:id="@+id/progress_bar" 
            style="?android:attr/progressBarStyleSmall" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:paddingRight="10dp" />

        <TextView android:id="@+id/progress_text" 
            android:layout_toRightOf="@id/progress_bar"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="First text" />

</RelativeLayout>

<TableLayout
    android:id="@+id/buttonbar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:paddingTop="3dip"
    android:background="@color/buttonbar"
    android:stretchColumns="0,1">

    <TableRow>

        <Button android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button1" />

        <Button android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button2" />

    </TableRow>

</TableLayout>

在代码中,我有一个可运行的函数,在几秒钟后更改progress_text TextView上的文本。

private Runnable mTimeTask = new Runnable() {

   public void run() {
       TextView progressText = (TextView) findViewById(R.id.progress_text);
       progressText.setText("Second text");
   }

};

问题在于这个setText()之后,一旦我聚焦在其中一个按钮上,文本就失去了居中对齐的效果,而变成了左对齐。我做错了什么?

我曾经遇到过这个问题,但按钮的文本变成了底部对齐。我在这里发布了一个新的问答,附带我的解决方案,其中涉及隐藏和显示按钮。http://stackoverflow.com/questions/28514288/buttons-text-gets-wrong-alignment-after-a-settext-call-on-a-textview - dodgy_coder
3个回答

7

我也遇到了这个问题。似乎setText()会改变重力设置,所以我不得不使用以下代码重新应用它们:

button.setGravity(Gravity.CENTER_HORIZONTAL);

3
尝试将填充重置为以下值:
button.setPadding(left, top, right, bottom);
使用如下数值:
button.setPadding(0, 0, 0, 0);

好的答案。如果按钮有内置填充,则重力不一定会将文本放在您想要的位置。 - Matt Logan

0

这里的所有答案都对我没用,所以我尝试找到自己解决问题的方法,并且在处理一个具有相同对齐问题的TextView时,我添加了一行android:maxLines="1",它突然就起作用了,所以我尝试在按钮上使用它,结果也奏效。

只需将android:maxLines="1"添加到您的按钮定义中,设置新文本后,文本对齐方式应该保持不变。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接