0

I have activity_main.xml layout file and I created landscape layout file in "layout-land" directory. Obviously both files have the same names.

Landscape and main layouts work good, but when I move my phone to swich layout, all my textViews and editTextes changes to default values.

2 Answers2

0

You have to save your information in a bundle and restore it during OnCreate().

https://developer.android.com/training/basics/activity-lifecycle/recreating.html

Kyle
  • 508
  • 6
  • 23
0

Every time you rotate your phone, configuration change happen and a new instance of your activity is created. That's why your Textview and Edittext are set to default values. However, if your views have id's set on them in the xml, then the values set on them will not be lost during a configuration change. If you don't want to set id then another way would be to save your Textview and Edittext values in onSaveInstanceState and restoring them in onRestoreInstanceState. For example to save your textview and edittext values follow the following code:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("arg1", textview1.getText());
    outState.putString("arg2", edittext1.getText().toString());
    ......
}

To restore the saved values follow following code:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    textview1.setText(savedInstanceState.getString("arg1"));
    edittext1.setText(savedInstanceState.getString("arg2"));
    ......
}

You can read more about this here: https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en

Harry
  • 923
  • 8
  • 24
  • My Textview and Edittext have ids in both xml layout files and it does not work. I will try saving and restoring variable, thanks for great response. –  Jul 02 '16 at 16:21
  • sorry I failed to mention that the id's should be unique and same in both layouts i.e. portrait and landscape. – Harry Jul 02 '16 at 16:40
  • of course I have the same IDs in both layouts for each View, but what do you mean "unique" IDs? Right now i have main_layout and landscape_layout which are the same files. I know that I can make it with Bundle, but I'm just curious if I can make it without Bundle :) –  Jul 02 '16 at 20:38