2017-04-27 27 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被調用。這個方法永遠不會被調用,因爲第一個指令 –