Locking Android orientation based on preference

非 Y 不嫁゛ 提交于 2019-12-24 18:41:53

问题


No, not a regurgitation of the old question, please, bear with me. I don't want to avoid activity recreation in general (no android:configChanges in manifest), I don't want to fix my orientation permanently (no android:screenOrientation in manifest) just because I'm lazy to implement instance saving.

I have an app with three possible settings the user can make: 1. automatically changing layout on orientation, as per normal, 2. fixed portrait, 3. fixed landscape. It makes sense in my case because the portrait and landscape displays show different functionality and the user might want to restrict to just one. Doesn't have to but has the possibility.

The app works just fine. I read the preference setting in onCreate and call setRequestedOrientation if I'm in one of the fixed modes. I let the system handle the orientation changes, I don't ask for handling the changes myself.

The only performance problem is that when, for instance, the app is started in the device's portrait position but fixed to landscape, onCreate will be called twice, once for the original startup, once for setRequestedOrientation. It works flawlessly, I handle it perfectly but there is a performance penalty, the activity appears with an obvious delay. (With screenOrientation fixed in the manifest, only for the purpose of testing, the startup looks much better, with only a single call to onCreate).

So, what I'm looking for is a kind of code equivalent of the manifest screenOrientation setting. I can't and don't want to specify it in the manifest but calling it from onCreate is already a bit late for performance.


回答1:


Try to read users preference in Application Class, and in the onCreate setContentView on the basis of that value.

public class MyApp extends Application{
  public void onCreate(){
   // get user preference here in a global variable
   }
}

Set this as application class in Manifest.

Then in your activities onCreate, use this value to determine layout before setContentView().




回答2:


did you try this?

<activity
        android:name=".YourActivity"
        android:configChanges="orientation|keyboard|keyboardHidden|screenSize|screenLayout|uiMode" />

This configChanges line on the manifest file should avoid the re-calling to the onCreate method :)



来源:https://stackoverflow.com/questions/56828044/locking-android-orientation-based-on-preference

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