- 在配置文件AndroidManifest.xml中配置权限
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>
- 在配置文件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>
- 在相应的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);// 横屏时显示的布局
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。