Android橫豎屏切換

凌浩雨發表於2017-08-16
  1. 在配置檔案AndroidManifest.xml中配置許可權
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>
  1. 在配置檔案AndroidManifest.xml中的activity接下內配置屬性
    android:configChanges="keyboard|screenSize|orientation|layoutDirection"
    application接下配置如下:
<application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:configChanges="keyboard|screenSize|orientation|layoutDirection"
        >
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
  1. 在相應的Activity中重寫onConfigurationChanged方法,在此方法中獲取螢幕的資訊。
  public void HalfScreen(View view) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  }

  public void FullScreen(View view) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  }
@Override public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Log.e(TAG, "onConfigurationChanged: ");
    //newConfig.orientation獲得當前螢幕狀態是橫向或者豎向
    //Configuration.ORIENTATION_PORTRAIT 表示豎向
    //Configuration.ORIENTATION_LANDSCAPE 表示橫屏
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
      Toast.makeText(MainActivity.this, "現在是豎屏", Toast.LENGTH_SHORT).show();
      setContentView(R.layout.activity_main);// 豎屏時顯示的佈局
    }
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
      Toast.makeText(MainActivity.this, "現在是橫屏", Toast.LENGTH_SHORT).show();
      setContentView(R.layout.activity_main1);// 橫屏時顯示的佈局
    }
  }


相關文章