2011-10-07 13 views
17

Necesito ayuda para alternar entre el modo de pantalla completa. Tengo una configuración en una pantalla de preferencias para ir a pantalla completa. En onResume de mi actividad principal que tengo:Cambiar al modo de pantalla completa

if(mFullscreen == true) { 
       getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 
       getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); 

      } else 
      { 
       getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); 
       getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 

      } 

Pero esto no parece funcionar, ya que tiene que ser llamado antes setContentView ¿verdad?

... Pero también, tengo requestWindowFeature(Window.FEATURE_NO_TITLE); antes de setContentView y le quita el título Y la barra de estado ... ¿Alguien puede ayudarme?

--- Editar --- Bien, tuve un error que causaba que esto no funcionara. Entonces realmente lo hace. Ahora, solo necesito saber cómo alternar la barra de título.

Respuesta

22
private void setFullscreen(boolean fullscreen) 
{ 
    WindowManager.LayoutParams attrs = getWindow().getAttributes(); 
    if (fullscreen) 
    { 
     attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 
    } 
    else 
    { 
     attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; 
    } 
    getWindow().setAttributes(attrs); 
} 
3

Mi solución combina respuestas de: Respuesta

añadí estos métodos a mi actividad. Para alternar entre pantalla completa, use setFullScreen(!isFullScreen()).

public boolean isFullScreen() { 

    return (getWindow().getAttributes().flags & 
     WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0; 
} 

@SuppressLint("NewApi") 
public void setFullScreen(boolean full) { 

    if (full == isFullScreen()) { 
     return; 
    } 

    Window window = getWindow(); 
    if (full) { 
     window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    } else { 
     window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    } 

    if (Build.VERSION.SDK_INT >= 11) { 
     if (full) { 
      getActionBar().hide(); 
     } else { 
      getActionBar().show(); 
     } 
    } 
} 

En mi caso, quería un botón de menú para hacer el alternar. El problema: en un dispositivo sin un botón de menú de hardware, ocultar la barra de acción también oculta el alternar para volver desde la pantalla completa. Entonces, agregué un poco de lógica adicional para que solo oculte la barra de acciones si el dispositivo tiene un botón de menú de hardware. Tenga en cuenta que los dispositivos con SDK 11-13 no tienen uno.

if (Build.VERSION.SDK_INT >= 14 
     && ViewConfiguration.get(this).hasPermanentMenuKey()))) { 

     if (full) { 
      getActionBar().hide(); 
     } else { 
      getActionBar().show(); 
     } 
    } 

Los dispositivos antiguos (que ejecutan Gingerbread o anterior) tienen una barra de título en lugar de una barra de acciones. El siguiente código lo ocultará, pero tenga en cuenta que la barra de título no se puede mostrar/ocultar una vez que la actividad ha comenzado. Incluí un mensaje para el usuario en mi menú de ayuda que indica que los cambios en la pantalla completa pueden no tener pleno efecto en los dispositivos más antiguos hasta que reinicien la aplicación/actividad (lo cual por supuesto supone que persiste su selección y ejecuta este código solo si lo desean) pantalla completa).

// call before setContentView() 
    if (Build.VERSION.SDK_INT < 11) { 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
    } 
6

Desde Jellybean (4.1) existe un nuevo método que no depende de WindowManager. En su lugar, use setSystemUiVisibility fuera de la ventana, esto le da un control más granular sobre las barras del sistema que utilizando los indicadores de WindowManager. Esta es la forma de habilitar a pantalla completa:

if (Build.VERSION.SDK_INT < 16) { //ye olde method 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
        WindowManager.LayoutParams.FLAG_FULLSCREEN); 
} else { // Jellybean and up, new hotness 
    View decorView = getWindow().getDecorView(); 
    // Hide the status bar. 
    int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; 
    decorView.setSystemUiVisibility(uiOptions); 
    // Remember that you should never show the action bar if the 
    // status bar is hidden, so hide that too if necessary. 
    ActionBar actionBar = getActionBar(); 
    actionBar.hide(); 
} 

Y esta es la forma de revertir el código anterior:

if (Build.VERSION.SDK_INT < 16) { //ye olde method 
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 
} else { // Jellybean and up, new hotness 
    View decorView = getWindow().getDecorView(); 
    // Hide the status bar. 
    int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE; 
    decorView.setSystemUiVisibility(uiOptions); 
    // Remember that you should never show the action bar if the 
    // status bar is hidden, so hide that too if necessary. 
    ActionBar actionBar = getActionBar(); 
    actionBar.show(); 
} 
+0

Tenga en cuenta que puede necesitar llamar 'getSupportActionBar()' en su lugar. – JakeSteam

+0

Uso este método, en la barra de estado de la máquina huawei se ha ocultado, pero la vista no puede ajustar automáticamente la ubicación en la parte superior de la pantalla – Carl

3

Hay un corto de palanca completa implementación del método de pantalla:

private void toggleFullscreen() { 
    WindowManager.LayoutParams attrs = getWindow().getAttributes(); 
    attrs.flags ^= WindowManager.LayoutParams.FLAG_FULLSCREEN; 
    getWindow().setAttributes(attrs); 
} 

Se utiliza bit a bit Lógica XOR para alternar FLAG_FULLSCREEN.

8
/** 
* toggles fullscreen mode 
* <br/> 
* REQUIRE: android:configChanges="orientation|screenSize" 
* <pre> 
* sample: 
*  private boolean fullscreen; 
*  ................ 
*  Activity activity = (Activity)context; 
*  toggleFullscreen(activity, !fullscreen); 
*  fullscreen = !fullscreen; 
* </pre> 
*/ 
private void toggleFullscreen(Activity activity, boolean fullscreen) { 
    if (Build.VERSION.SDK_INT >= 11) { 
     // The UI options currently enabled are represented by a bitfield. 
     // getSystemUiVisibility() gives us that bitfield. 
     int uiOptions = activity.getWindow().getDecorView().getSystemUiVisibility(); 
     int newUiOptions = uiOptions; 
     boolean isImmersiveModeEnabled = 
       ((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions); 
     if (isImmersiveModeEnabled) { 
      Log.i(context.getPackageName(), "Turning immersive mode mode off. "); 
     } else { 
      Log.i(context.getPackageName(), "Turning immersive mode mode on."); 
     } 

     // Navigation bar hiding: Backwards compatible to ICS. 
     if (Build.VERSION.SDK_INT >= 14) { 
      newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; 
     } 

     // Status bar hiding: Backwards compatible to Jellybean 
     if (Build.VERSION.SDK_INT >= 16) { 
      newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN; 
     } 

     // Immersive mode: Backward compatible to KitKat. 
     // Note that this flag doesn't do anything by itself, it only augments the behavior 
     // of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample 
     // all three flags are being toggled together. 
     // Note that there are two immersive mode UI flags, one of which is referred to as "sticky". 
     // Sticky immersive mode differs in that it makes the navigation and status bars 
     // semi-transparent, and the UI flag does not get cleared when the user interacts with 
     // the screen. 
     if (Build.VERSION.SDK_INT >= 18) { 
      newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; 
     } 
     activity.getWindow().getDecorView().setSystemUiVisibility(newUiOptions); 
    } else { 
     // for android pre 11 
     WindowManager.LayoutParams attrs = activity.getWindow().getAttributes(); 
     if (fullscreen) { 
      attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 
     } else { 
      attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; 
     } 
     activity.getWindow().setAttributes(attrs); 
    } 

    try { 
     // hide actionbar 
     if (activity instanceof ActionBarActivity) { 
      if (fullscreen) ((ActionBarActivity) activity).getSupportActionBar().hide(); 
      else ((ActionBarActivity) activity).getSupportActionBar().show(); 
     } else if (Build.VERSION.SDK_INT >= 11) { 
      if (fullscreen) activity.getActionBar().hide(); 
      else activity.getActionBar().show(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    // set landscape 
    // if(fullscreen) activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); 
    // else activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); 
} 

mi código funciona bien con Android 2.3 y 4.4.2

+2

¡Excelente método de actualización! Sin embargo, hay dos cosas: 1) a las modificaciones de newUiOptions les faltan las partes "& = ~ xxx" que no son de pantalla completa, 2) La versión más reciente de la aplicación de compatibilidad usa AppCompatActivity en lugar de ActionBarActivity. –

+0

grandes gracias trabajado para mí – Richi

Cuestiones relacionadas