Android: Detectar la orientación cambiada

Necesito detectar un cambio de orientación en mi aplicación, pero no quiero que mi diseño cambie de retrato a paisaje. Actualmente estoy utilizando el OrientationEventListener sin embargo detectar el ángulo de orientación no es suficiente. Quiero detectar que el usuario cambió de retrato a paisaje o viceversa, y que no es sólo detectar si el ángulo de orientación es 90 o 270.

Quiero hacer la misma detección que hace el Android para cambiar la orientación de la actividad. Intenté sobreescribir onConfigurationChanged y comprobar si orientantion es paisaje / retrato, sin embargo esto todavía cambia mi disposición de la actividad al paisaje.

¿Hay una manera de usar onConfigurationChanged pero forzar el diseño para permanecer en el retrato?
¿Existe otra manera de detectar el cambio de orientantion sin usar OrientationEventListener . En última instancia, puedo implementar mi propia orientación algoritmo cambiado, cualquier idea sobre esto? Tiene que ser algo más complejo que if(90-THRESHOLD <= orientation <= 90+THRESHOLD) , quiero detectar si el usuario realizó el movimiento completo Retrato-> Paisaje o Paisaje-> Retrato.

Gracias por la ayuda,
Filipe

Ok, después de intentar usar la API de Android y no poder hacer lo que necesito, implementé mi propio algoritmo y en realidad no fue tan complicado: usé un OrientationEventListener y calculé si la orientación está en los 4 puntos de orientación En mi código sólo detecto LANDSCAPE_RIGHT y PORTRAIT_UP :

 orientationListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_UI) { public void onOrientationChanged(int orientation) { if(canShow(orientation)){ show(); } else if(canDismiss(orientation)){ dismiss(); } } }; @Override public void onResume(){ super.onResume(); orientationListener.enable(); } @Override public void onPause(){ super.onPause(); orientationListener.disable(); } private boolean isLandscape(int orientation){ return orientation >= (90 - THRESHOLD) && orientation <= (90 + THRESHOLD); } private boolean isPortrait(int orientation){ return (orientation >= (360 - THRESHOLD) && orientation <= 360) || (orientation >= 0 && orientation <= THRESHOLD); } public boolean canShow(int orientation){ return !visible && isLandscape(orientation); } public boolean canDismiss(int orientation){ return visible && !dismissing && isPortrait(orientation); } 

Hi screamingnoises es esto lo que estás buscando?

 // Set background image, rotatable View view = getWindow().getDecorView(); int orientation = getResources().getConfiguration().orientation; if (Configuration.ORIENTATION_LANDSCAPE == orientation) { //Do SomeThing; // Landscape } else { //Do SomeThing; // Portrait } 

Creé la siguiente clase para detectar cambios de orientación, manteniendo la orientación original de mi actividad:

 public class SensorOrientationChangeNotifier { public final String TAG = getClass().getSimpleName(); private ArrayList<WeakReference<SensorOrientationChangeNotifier.Listener>> mListeners = new ArrayList<WeakReference<SensorOrientationChangeNotifier.Listener>>(3); private int mOrientation = 0; private SensorEventListener mSensorEventListener; private SensorManager mSensorManager; private static SensorOrientationChangeNotifier mInstance; public static SensorOrientationChangeNotifier getInstance() { if (mInstance == null) mInstance = new SensorOrientationChangeNotifier(); return mInstance; } private SensorOrientationChangeNotifier() { mSensorEventListener = new NotifierSensorEventListener(); Context applicationContext = GlobalData.getInstance().getContext(); mSensorManager = (SensorManager) applicationContext.getSystemService(Context.SENSOR_SERVICE); } /** * Call on activity reset() */ private void onResume() { mSensorManager.registerListener(mSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } /** * Call on activity onPause() */ private void onPause() { mSensorManager.unregisterListener(mSensorEventListener); } private class NotifierSensorEventListener implements SensorEventListener { @Override public void onSensorChanged(SensorEvent event) { float x = event.values[0]; float y = event.values[1]; int newOrientation = mOrientation; if (x < 5 && x > -5 && y > 5) newOrientation = 0; else if (x < -5 && y < 5 && y > -5) newOrientation = 90; else if (x < 5 && x > -5 && y < -5) newOrientation = 180; else if (x > 5 && y < 5 && y > -5) newOrientation = 270; //Log.e(TAG,"mOrientation="+mOrientation+" ["+event.values[0]+","+event.values[1]+","+event.values[2]+"]"); if (mOrientation != newOrientation){ mOrientation = newOrientation; notifyListeners(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } } public int getOrientation() { return mOrientation; } public interface Listener { void onOrientationChange(int orientation); } public void addListener(SensorOrientationChangeNotifier.Listener listener) { if (get(listener) == null) // prevent duplications mListeners.add(new WeakReference<SensorOrientationChangeNotifier.Listener>(listener)); if (mListeners.size() == 1) { onResume(); // this is the first client } } public void remove(SensorOrientationChangeNotifier.Listener listener) { WeakReference<SensorOrientationChangeNotifier.Listener> listenerWR = get(listener); remove(listenerWR); } private void remove(WeakReference<SensorOrientationChangeNotifier.Listener> listenerWR) { if (listenerWR != null) mListeners.remove(listenerWR); if (mListeners.size() == 0) { onPause(); } } private WeakReference<SensorOrientationChangeNotifier.Listener> get(SensorOrientationChangeNotifier.Listener listener) { for (WeakReference<SensorOrientationChangeNotifier.Listener> existingListener : mListeners) if (existingListener.get() == listener) return existingListener; return null; } private void notifyListeners() { ArrayList<WeakReference<SensorOrientationChangeNotifier.Listener>> deadLiksArr = new ArrayList<WeakReference<SensorOrientationChangeNotifier.Listener>>(); for (WeakReference<SensorOrientationChangeNotifier.Listener> wr : mListeners) { if (wr.get() == null) deadLiksArr.add(wr); else wr.get().onOrientationChange(mOrientation); } // remove dead references for (WeakReference<SensorOrientationChangeNotifier.Listener> wr : deadLiksArr) { mListeners.remove(wr); } } public boolean isPortrait(){ return mOrientation == 0 || mOrientation == 180; } public boolean isLandscape(){ return !isPortrait(); } } 

Utilícelo de la siguiente manera:

En AndroidManifest.xml –

  <activity ... android:screenOrientation="portrait" > 

En su actividad:

 public class MainActivity extends Activity implements SensorOrientationChangeNotifier.Listener { @Override protected void onResume() { super.onResume(); SensorOrientationChangeNotifier.getInstance().addListener(this); } @Override protected void onPause() { super.onPause(); SensorOrientationChangeNotifier.getInstance().remove(this); } @Override public void onOrientationChange(int orientation) { if (orientation == 90 || orientation == 270){ // Do some landscape stuff } else { // Do some portrait stuff } } } } 
  int orientation = getResources().getConfiguration().orientation; isPortrait = Configuration.ORIENTATION_PORTRAIT == orientation; 

Para detectar la orientación, pediremos a la actividad que nos proporcione el ancho y la altura de la actividad, de modo que podamos encontrar si Ancho> Altura que será "Paisaje" o Altura> Ancho que sea "Retrato" – El siguiente código es Probado y trabajando.

 @SuppressWarnings("deprecation") public void detectScreenOrientation(){ WindowManager wm = getWindowManager(); Display d = wm.getDefaultDisplay(); if (d.getWidth() > d.getHeight()){ Log.d("Orientation","Landscape mode"); } else { Log.d("Orientation", "Portrait mode"); } } 
  • Fragmentos anidados pierden llamadas a onCreateOptionsMenu después de rotación de pantalla
  • Apoyo a las dos orientaciones del paisaje en Honeycomb
  • Problemas al manejar los cambios de orientación
  • La lista desplegable de Spinner y la orientación de la pantalla cambian el problema
  • Android ListFragment no guarda el paquete en onSaveInstanceState () / no recupera el bundle en onActivityCreated ()
  • Cordova ignora el bloqueo de la orientación de la pantalla
  • Emulador de panal invertido pantalla en retrato
  • Cambiar la orientación de la pantalla mediante un botón
  • Cómo manejar los cambios de orientación de la pantalla cuando hay una asyntax ejecutando con android 4.x
  • Cambio de orientación de la pantalla de la tableta: no se ha encontrado ninguna vista para id para Fragment
  • Bloquear la orientación hasta que termine Asíntate
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.