Android 8 - How to know what side the Navigation B

2019-08-22 09:42发布

问题:

In Android 8, when the phone goes to LANDSCAPE the navigation will be on the right side of the screen, and when its in REVERSE_LANDSCAPE, it'll be on the left side. What I did to find out which side of the screen it is on was to have the root View of my activity and check it's size and position in these ways:

if (rootView.width == deviceScreenWidth) {
    // device is tablet and the navigation bar is at the bottom, or
    // its a samsung device with no navigation bar
} 
else if (rootView.positionOnScreenX == 0) {
    // the navigation bar is at the LEFT side
} 
else {
    // the navigation bar is at the RIGHT side
}

But I'm facing a new problem regarding this approach, which is if user goes directly from LANDSCAPE to REVERSE_LANDSCAPE navigation bar will change location, but the code doesn't run again which causes problems.

Is there any callbacks in android sdk to listen to this rotation? Or is there a better way to know which side of the screen the navigation bar is, without running into this problem?

回答1:

You can override Activity#onConfigurationChanged(Configuration newConfig) to get a callback when the user rotates their device.

You can checkout these links for more details:

  • https://developer.android.com/guide/topics/resources/runtime-changes

  • https://developer.android.com/reference/android/app/Activity#onConfigurationChanged(android.content.res.Configuration)