简体   繁体   中英

How to handle activity orientation change to dont recreate the activity?

I start an activity with startActivityForResult() but after the orientatikn changed and i return to the onActivityResult() method the requestCode not the same. I would like to use different layout if the screen orientation is in landscape mode. I tried in the manifest the configuration with orientation and screenSize params, but if i use this the layout not changed to the landscape layout. I started the activity with requestCode=0 but after the orientation changed i see that the requestCode = 66357 or something.

Create two types of the layout folders. "layout-land" and "layout-port". put the required xml in both the directory with same name.

you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity.

In your AndriodMainfest.xml define configChanges

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

Then in your ResultActivity.java(that you call to get result) define onConfigurationChanged()

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

official link

You have two options:

A)Set your app to not rotate.

B)Or accept that the world is not perfect yet and modify your app to handle configuration change

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM