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

时间:2010-11-16 14:52:45

标签: android text button alignment

我正在使用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>

在代码中,我有一个runnable,几秒后就会改变progress_text TextView上的文本。

private Runnable mTimeTask = new Runnable() {

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

};

问题是在这个setText()之后,一旦我专注于其中一个按钮,文本就会失去它的居中对齐并一直向左移动。我做错了什么?

3 个答案:

答案 0 :(得分:7)

我也有这个问题。似乎setText()更改了重力设置,因此我必须使用以下方法重新应用它们:

button.setGravity(Gravity.CENTER_HORIZONTAL);

答案 1 :(得分:3)

尝试将其填充重置为:

button.setPadding(left, top, right, bottom);

有价值:

button.setPadding(0, 0, 0, 0);

答案 2 :(得分:0)

这里没有任何答案对我有用,所以我试图找到自己的方法来修复它并且弄乱了具有相同对齐问题的TextView但是当我添加了行android:maxLines="1"时它突然起作用了所以我在按钮上尝试了它并且它有效。

只需将android:maxLines="1"添加到按钮的定义中,并在设置新文本后保留文本对齐方式。