当设备旋转时,TextView的文本消失

时间:2012-01-16 11:37:48

标签: android textview

我正在为Android编写一个电话拨号器应用程序。我为键盘创建了一个布局,其中包含一个TextView和10个按钮。按钮是10位数字(0到9)的键,TextView用于根据按下的键显示数字。

在我的应用程序中,我为每个按下的按钮将文本(“0”或“1”等)附加到TextView。如果我按下按钮1,2,3 ,则TextView上的文本为123 。 问题是,让屏幕处于横向模式,TextView包含123,如果我转动它,在纵向模式下TextView上没有文字。

请帮助我。

5 个答案:

答案 0 :(得分:14)

@jeet推荐的内容对我不起作用。我不得不添加“screenSize”。这是您应该在活动的<activity>节点的manifest.xml中添加的行:

android:configChanges="keyboardHidden|orientation|screenSize"

因此,完整节点可能如下所示:

<activity
android:name=".YourActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="@style/AppTheme.NoActionBar">

答案 1 :(得分:7)

请检查方向更改,调用create方法,这需要再次创建所有视图,因此您需要使用以下方法之一:

  1. 使用onSavedInstance方法并将组件/视图的状态保存到bundle。
  2. 在活动代码android:configChanges =“keyboardHidden | orientation”的清单文件中使用以下标志为true。如下所示:

    <activity android:name=".SampleActivity" android:label="@string/app_name"
        android:configChanges="keyboardHidden|orientation">
        ...
    </activity>
    

答案 2 :(得分:7)

之所以这样,是因为Android每次旋转设备时都会破坏活动并再次创建活动。这主要是为了允许基于纵向/横向模式的不同布局。

处理此问题的最佳方法是通过响应onSavedInstance事件(在Android销毁活动之前调用),然后在标准中重新应用这些数据来存储您需要保留在活动Bundle中的任何数据。 onCreate事件。

虽然您可以为configChanges属性添加“orientation”,但请记住,您基本上是在告诉Android您将自己处理与方向更改相关的所有内容 - 包括更改布局等等。

答案 3 :(得分:0)

如果有人仍然遇到麻烦......这对我来说就是这个伎俩

public class BranjeKP extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_branje_kp);

    //...
}

@Override
protected void onSaveInstanceState(Bundle out) {
    super.onSaveInstanceState(out);
    out.putString("TVNazivPod", TVNazivPodatka.getText().toString());
    out.putString("TVEnotaMere", TVEnotaMere.getText().toString());
}

@Override
protected void onRestoreInstanceState(Bundle in) {
    super.onRestoreInstanceState(in);
    TVNazivPodatka.setText(in.getString("TVNazivPod"));
    TVEnotaMere.setText(in.getString("TVEnotaMere"));
}

您基本上将旋转前所需的任何值(即调用onSaveInstanceState时)保存到Bundle中,旋转后(onRestoreInstanceState)只需将所有值从Bundle中拉出。 为了澄清,TVNazivPodatka和TVEnotaMere是TextView小部件。

......在...的帮助下 How to prevent custom views from losing state across screen orientation changes

答案 4 :(得分:0)

要保留TextView的文本,只需将TextView的 freezesText 属性设置为 true 即可。 如:

    <TextView
    ...
    android:freezesText="true"
    .../>

这是这里接受的答案: Restoring state of TextView after screen rotation?

相关问题