2017-04-27 28 views
0

我需要锁定一个片段的布局,以防止它在设备旋转到横向时旋转。防止布局更改,仍然捕捉配置ChangeChanged

为了做到这一点,我把它锁进清单:

android:screenOrientation="portrait 

布局并没有改变,但我仍然需要做的,当方向改变一些工作(旋转按钮)。以这种方式锁定它可以防止调用onConfigurationChanged。

我所瞄准的行为完全像默认相机应用程序。旋转设备时,布局保持不变,但只有按钮旋转。

有没有人有这样做的伎俩?

回答

1

如果你要听简单的屏幕方向改变编程,有你应用程序对它们做出反应,您可以使用the OrientationEventListener类在您的Activity中执行此操作。

在活动中实现方向事件处理很简单。只需实例化一个OrientationEventListener并提供它的实现。例如,下面的活动类称为SimpleOrientationActivity日志方位信息的logcat:

public class SimpleOrientationActivity extends Activity { 
    OrientationEventListener mOrientationListener; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     mOrientationListener = new OrientationEventListener(this, 
      SensorManager.SENSOR_DELAY_NORMAL) { 

      @Override 
      public void onOrientationChanged(int orientation) { 
       Log.v(DEBUG_TAG, 
        "Orientation changed to " + orientation); 
      } 
     }; 

     if (mOrientationListener.canDetectOrientation() == true) { 
      Log.v(DEBUG_TAG, "Can detect orientation"); 
      mOrientationListener.enable(); 
     } 
     else { 
      Log.v(DEBUG_TAG, "Cannot detect orientation"); 
      mOrientationListener.disable(); 
     } 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     mOrientationListener.disable(); 
    } 
} 

如需更多帮助,请参阅this

this answer将帮助。

+0

我认为会有一个内置的方法来做到这一点,使用screenOrientation和OnConfigurationChanged,但这会做到这一点。谢谢:) –

+0

在这种情况下,你需要覆盖'public void onOrientationChanged()'... – rafsanahmad007

0

您可以通过编程设置方向:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE); 

并使用此检测代码取向的变化:

@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    // Do something here... 
} 
+0

正如我在原来的文章中指出的,以某种方式锁定屏幕将阻止onConfigurationChanged被调用。这个方法永远不会被调用,因为第一个指令 –