Android : Activity created twice when called setRequestedOrientation() to display in Landscape mode

on Saturday, October 25, 2014


I have an app for Android, I want to force tablet (sw600dp and higher) to display in Landscape mode and phone to display in Portrait mode, so I handle in onCreate of my BaseActivity class



boolean isTablet= getResources().getBoolean(R.bool.isTablet);
if (isTablet) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}


And the way I put "isTablet" in bools.xml file and put it in


values folder for phone



<resources>
<bool name="isTablet">false</bool>
</resources>


values-sw600dp for tablet



<resources>
<bool name="isTablet">true</bool>
</resources>


And in AndroidManifest I use



android:screenOrientation="nosensor"


just ensure to disable device orientation's sensor.


It seems to be my approach works fine (Landscape for tablet and Portrait for phone) BUT the problem happens when I run my app on Nexus 7 - my activities create twice. These steps are:



  1. Hole Nexus 7 in Portrait (it's fine if I hold tablet in Landscape)

  2. Then run the app


I find that the problem is the method setRequestedOrientation() (with 2 steps above). So I don't want to call that method anymore. I try to set orientation in AndroidManifest like:



android:screenOrientation="@integer/orientation"


Because: SCREEN_ORIENTATION_LANDSCAPE = 0 SCREEN_ORIENTATION_PORTRAIT = 1


I declare "orientation" in integers.xml file and put it in


values folder for phone



<resources>
<integer name="orientation">1</integer>
</resources>


values-sw600dp for tablet



<resources>
<integer name="orientation">0</integer>
</resources>


Again, my approach tends to works fine BUT I find that AndroidMenifest just understands "orientation" in values folder, not in values-sw600dp folder. I don't want my activities to call 2 times. Did you have a problem like that?? Could you solve it? Thanks.


0 comments:

Post a Comment