I am trying to lock the phone to portrait and tablet to landscape. I usually use AndroidManifest.xml - android:screenOrientation="portrait" But how can I set orientation to tablet / phone differently? Thanks!
4 Answers
The best solution is to load one parameter from res folder from specific value. So if Your app is running on tablet, the screen density must be great or equals to 600dp.
In folder: res/values-sw600dp/ create xml with param:
<resources>
<bool name="isTablet">true</bool>
</resources>
In folder res/values/ create xml with param
<resources>
<bool name="isTablet">false</bool>
</resources>
After that You will be able check if app is running on tablet or phone by using this code:
boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Source from:
https://stackoverflow.com/a/9308284/619673
https://developer.android.com/guide/practices/screens_support.html
First check whether device is smartphone or tablet then you can set the orientation of your activity by using below code
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
or
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
and you can check Determine if the device is a smartphone or tablet?
First you can detect whether your app is running on smartphone or a tablet for that please see following answer
Now you can lock orientation using following code:
If(isTablet)
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Use Java code. In java class that you want to make special orientation, use this code:
if ((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE) {
// on a X large screen device ...
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if ((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE) {
// on a large screen device ...
// do everythings you want to do ...
} else {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
and in fragment use "getActivity()" instead of "this". And for make view flexible with device use this code:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
Maybe worked. Good luck.
lamers
? – Phantômaxx