简体   繁体   中英

android - how to finish an activity when the orientation is changed?

What I'm trying to do is to close the Activity if the user is changing the orientation in the middle of the use.

I have added to this activity the following line in the manifest -

android:configChanges="orientation"

and I have also overridden onConfigurationChanged :

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

But it seems that it doesn't do the trick, so what am I doing wrong here?

Also add keyboardHidden and screenSize.

android:configChanges="orientation|keyboardHidden|screenSize"

NOTE : screenSize is only if your application targets API level 13 or higher.

I don't think this behaviour is good for users. If they accidentally rotate the device the app will immediately close? What about devices that default to landscape (some tablets and chromebooks)? Users will assume your app is buggy and has crashed. Or is it a game that hits the "Game Over" case the user if they accidentally rotate their device? (ie. maybe balancing their phone on their nose?)

In order of desirability for most apps:

  1. Have the app function well in any orientation. Make sure it handles orientation changes by moving long-running operations to background threads and view state to a ViewModel.
  2. If this is a quick demo / sample, and you have a short task that you don't want to interrupt and don't want to invest in moving it correctly to a background thread, use setRequestedOrientation ( SCREEN_ORIENTATION_LOCKED ) and then set it back to SCREEN_ORIENTATION_SENSOR .
  3. Lock the app to portrait. :( don't do this.
int a=3;

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

// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    if(a==3 || a==0)
    { 
      a=0;
    }else
{ finish(); }
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
    if(a==3 || a==1)
    { 
      a=0;
    }else
{ finish(); }
}
}

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