TextView 更改按钮单击的位置?

TextView changes position on buttonClick?

所以一个简短的问题...

我遇到了一个以前从未遇到过的问题。 我有一个 TextView 显示一条消息,该消息位于 LinnearLayout 中,Gravity 设置为 center_horizontal。按下按钮 - 同一个 TextView 的文本与我资源中的另一个字符串交换。

但是,当我按下按钮时,重力发生变化 (?) 并且 TextViews 位置现在位于左侧而不是中心...

知道是什么原因造成的吗?

这是我的代码: 字符串资源:

<string name="welcome_message">
    WELCOME, USER!
</string>

<string name="calculating_message">
    CALCULATING ORIENTATION...
</string>

XML:

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

        <TextView
            android:id="@+id/tvMessage"
            android:layout_marginTop="50dp"
            android:textColor="@android:color/white"
            android:text="@string/welcome_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30dp"/>
</LinearLayout>

代码:

public void initializeComponents() {

        //textview
        tvMessage = (TextView) findViewById(R.id.tvMessage);

        //button
        btnGo = (Button) findViewById(R.id.btnGo);
            btnGo.setOnClickListener(new btnGoListener());
        }

private class btnGoListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            tvMessage.setText(R.string.calculating); 
        }
    }

资源中的字符串值发生更改时未遵循正确的命名约定准则。 Textview 位置的变化是由于两个变化 layout_gravity 和 gravity 最好看看它们之间的区别。我希望这能解决您的问题,或者更好地 post 您的源代码。

您忘记了 android:textAlignment="center" 属性。您的文本对齐方式保持默认。

<TextView
    android:id="@+id/tvMessage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:text="@string/welcome_message"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="30dp" />

同时将 android:layout_width= 更改为 "match_parent"

抱歉英语不好。希望对你有帮助。