TextView contents is lost after changing screen orientation

微笑、不失礼 提交于 2019-12-04 02:56:48
Durairaj Packirisamy

Use this property in your TextView android:freezesText="true".

You can use the savedInstanceBundle to keep hold of the data by overriding two methods inside your activity, similar to below:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save state to the savedInstanceState
  savedInstanceState.putString("MyString", textview.getText());

}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore state from savedInstanceState
  String myString = savedInstanceState.getString("MyString");
  textview.setText(myString);
}

Add your items to the Bundle in onSaveInstanceState, and read them back in during onRestoreInstanceState. This works in a similar way to passing values through intents when creating activities.

When orientation changes happen, Android reload the Activity hence destroying most information like TextView changes. You will need to override onSaveInstanceState(), which will run before the screen orientation change happens. Then you will have access to it in your Bundle that is passed into onCreate. You should also reference this to understand the Activity Life cycle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!