Android虚拟导航栏显示隐藏监听
Android虚拟导航栏显示隐藏监听
部分手机自带虚拟导航栏,导航栏的显示/隐藏会引起一些布局问题。下面自定义虚拟导航栏监听,希望对大家有所帮助。
代码块
代码块语法遵循标准markdown代码,例如:
public class ScreenUtils {
/**
* 获取手机屏幕高度
*/
public static int getHeight() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) MApplication.getInstance().getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return dm.heightPixels;
}
/**
* 获取屏幕真实高度(包括虚拟键盘)
*
*/
public static int getRealHeight() {
WindowManager windowManager = (WindowManager) MApplication.getInstance().getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
display.getRealMetrics(dm);
} else {
display.getMetrics(dm);
}
int realHeight = dm.heightPixels;
return realHeight;
}
public interface NavigationListener {
void show();
void hide();
}
//虚拟导航栏显示/隐藏
public static void setNavigationListener(final View rootView, final NavigationListener navigationListener){
if (rootView == null || navigationListener == null) {
return;
}
if (getRealHeight() != getHeight()) {
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int rootViewHeight;
@Override
public void onGlobalLayout() {
int viewHeight = rootView.getHeight();
if (rootViewHeight != viewHeight) {
rootViewHeight = viewHeight;
if (viewHeight == getRealHeight()) {
//隐藏虚拟按键
if (navigationListener != null) {
navigationListener.hide();
}
} else {
//显示虚拟按键
if (navigationListener != null) {
navigationListener.show();
}
}
}
}
});
}
}
}
注:
1、getRealHeight()-getHeight()即为虚拟导航栏高度。
2、有个小问题就是调用此方法Activity未被销毁,即使跳转到其他activity,监听也会回调,这点可以根据自己需求优化。