Android Realization of Hiding Virtual Keys in Mobile Games

  • 2021-10-15 11:27:08
  • OfStack

Mobile games to achieve Android hidden virtual keys, for your reference, the specific contents are as follows

In Huawei and other models of mobile phones, there will be virtual buttons. When entering the game, you need to hide this button in full screen, and when you pull down the status bar, you will call out the virtual buttons again.

During the loading process of the game, initialize and check the update, and then enter the game screen, which is actually the switching of two view of android.

In MainActivity, add the following function in onCreate () method and override one method.


@Override
protected void onCreate(Bundle icicle) {
  hideNavigationBar();
}

//  Hide virtual keys 
public void hideNavigationBar()
{
  int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
    | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

  if( android.os.Build.VERSION.SDK_INT >= 19 ){
    uiFlags |= 0x00001000;  //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
  } else {
    uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
  }
  getWindow().getDecorView().setSystemUiVisibility(uiFlags);
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  if( hasFocus ) {
    hideNavigationBar();
  }
}

In addition, after switching to GameView, it was found that hiding is hidden, but the one virtual key is gray, and the rendering area of the game does not contain any area, so it is felt that the size of the rendering area is not correct after hiding the virtual key, and the real resolution of the screen should be obtained.
The following method is to get the true resolution of the screen, and then the rendering area is full screen, so that it can be displayed in full screen.


private Point getDisplay(MainActivity context)
{
  DisplayMetrics metrics = new DisplayMetrics();
  Display display = context.getWindowManager().getDefaultDisplay();
  display.getMetrics(metrics);
  DisplayMetrics dm = new DisplayMetrics();
  @SuppressWarnings("rawtypes")
  Class c;
  try {
    c = Class.forName("android.view.Display");
    @SuppressWarnings("unchecked")
    Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
    method.invoke(display, dm);
    return new Point(dm.widthPixels, dm.heightPixels);
  } catch (Exception e) {
    return new Point(dm.widthPixels, dm.heightPixels);
  }
}

Related articles: