Android 隐藏虚拟按键
领导要求:
- 横屏播放视频时,不展示虚拟按键;
- 恢复到竖屏时,展示虚拟按键;
/**
* NavigationBar 显示与隐藏
*/
public class NavigationBarHelper {
private Fragment fragment;
private boolean mSystemUiVisibilityUpdated;
// android 4.4 api19 及以上,记录竖屏时的SystemUiVisibility
private int mSystemUiVisibilityPortrait;
public NavigationBarHelper(Fragment fragment) {
this.fragment = fragment;
}
private View getDecorView() {
if (fragment != null
&& fragment.getActivity() != null) {
return fragment.getActivity().getWindow().getDecorView();
}
return null;
}
public void beforeOrientationChange(boolean targetLandscape) {
if (targetLandscape) {
hideBottomMenu();
} else {
showBottomMenu();
}
}
/**
* 竖屏 显示虚拟按键
*/
private void showBottomMenu() {
if (fragment != null && fragment.getActivity() != null) {
View decorView = getDecorView();
if (decorView != null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
decorView.setSystemUiVisibility(View.VISIBLE);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && mSystemUiVisibilityUpdated) {
// 恢复 竖屏时的SystemUiVisibility
decorView.setSystemUiVisibility(mSystemUiVisibilityPortrait);
mSystemUiVisibilityUpdated = false;
}
}
}
}
/**
* 横屏 隐藏虚拟按键
*/
private void hideBottomMenu() {
if (fragment != null && fragment.getActivity() != null) {
View decorView = getDecorView();
if (decorView != null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
decorView.setSystemUiVisibility(View.GONE);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (mSystemUiVisibilityUpdated) {
return;
}
// 记录竖屏时的SystemUiVisibility
mSystemUiVisibilityPortrait = decorView.getSystemUiVisibility();
// 隐藏虚拟按键
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
mSystemUiVisibilityUpdated = true;
}
}
}
}
/**
* 退出到后台 返回时
*/
public void onVideoResume() {
if (fragment != null && fragment.getActivity() != null) {
// 当前是横屏 播放视频
if (fragment.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
View decorView = getDecorView();
if (decorView != null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
decorView.setSystemUiVisibility(View.GONE);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 隐藏虚拟按键
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
}
}
}
}
}