ulquiorra
ulquiorra

Reputation: 945

manage screen orientation change android

I have a activity with multiples initializations ( fragments , sharedpreferences , services , ui components(search bar , buttons etc..)...) and i do not want to restart the activity when the screen orientation change

I found a easy ( and working solution ) by using android:configChanges="keyboardHidden|orientation|screenSize" but my technical manager forbade me this way because according to him it's a bad practice

What are the other ways in order to handle properly the screen orientation changes?

Thank you very much

My main activity

  @AfterViews
    public void afterViews() {
      putSharedPrefs();
      initializeFragments();
      initializeComponents();
      initializeSynchronizeDialog();
      initDownloadDialog();
    }

Upvotes: -1

Views: 654

Answers (1)

Kunal
Kunal

Reputation: 442

You can just add layout for landscape mode.
You just need to add folder layout-land in your "res" directory and define layout for what your activity looks like if it is in landscape mode.
NOTE-Keep xml file name same as the name which is in simple layout folder and which you are using in your activity. It will automatically detect your screen orientation and apply layout accordingly.
EDIT1
Now to save your text from the text view =) Lets assume your textview is named as MyTextView in your layout xml file. Your activity will need the following: private TextView mTextView; private static final String KEY_TEXT_VALUE = "textValue";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.main);
if (savedInstanceState != null) {
  String savedText = savedInstanceState.getString(KEY_TEXT_VALUE);
  mTextView.setText(savedText);
}

@Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_TEXT_VALUE, mTextView.getText());
}

Basically, whenever Android destroys and recreates your Activity for orientation change, it calls onSaveInstanceState() before destroying and calls onCreate() after recreating. Whatever you save in the bundle in onSaveInstanceState, you can get back from the onCreate() parameter.

So you want to save the value of the text view in the onSaveInstanceState(), and read it and populate your textview in the onCreate(). If the activity is being created for the first time (not due to rotation change), the savedInstanceState will be null in onCreate(). You also probably don't need the android:freezesText="true"

You can also try saving other variables if you need to, since you'll lose all the variables you stored when the activity is destroyed and recreated.

Upvotes: 5

Related Questions