Saturday, July 10, 2010

Android - Orientation lock on hard keyboard open/closed

Hi... I am back with a new problem and its solution.
I was struggling with the requirement where I had to lock the screens orientation with respect to the hard keyboard open/closed state. The problem was to lock the orientation in landscape when hard keyboard is open and lock the orientation in portrait when hard keyboard is closed.

Small trick might work.
put the below code in your activity you want to achieve this.

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
switch (newConfig.hardKeyboardHidden) {
case Configuration.HARDKEYBOARDHIDDEN_YES:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case Configuration.HARDKEYBOARDHIDDEN_NO:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}

Wait..... your are not done yet. What will happen when user comes in this activity with landscape mode already set.
In that case handling is done with one more trick.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Call the above in your onCreate method to signal the onConfigurationChanged and after that it will handle the orientation. :-)

Three cheers !!!

No comments:

Post a Comment