Android 横竖屏切换

  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);// 横屏时显示的布局
    }
  }
上一篇:(转)appium微信公众号H5页面自动化测试


下一篇:ESP32接入巴法云,开源安卓app、微信小程序控制