Android开发中如何强制横屏和强制竖屏设置
强制横屏设置:
按照下面代码示例修改Activity的onResume方法 @Override protected void onResume() { /** * 设置为横屏 */ if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } super.onResume(); }
或
或者在配置文件中对Activity节点添加android:screenOrientation属性(landscape是横向,portrait是纵向)
android:launchMode="singleTask" android:screenOrientation="landscape">
强制竖屏设置:
@Override protected void onResume() { /** * 设置为横屏 */ if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } super.onResume(); }
或者
在配置文件中对Activity节点添加android:screenOrientation属性(landscape是横向,portrait是纵向)
android:launchMode="singleTask" android:screenOrientation="portrait">
在AndroidManifest.xml的activity节点中添加如下片段:
<activity android:name="com.yogi.ScreenOrientationActivity" android:screenOrientation="portrait" //横屏改成:landscape即可。 > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
或者
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制竖屏
写在setContentView()之后即可
附:测试另一种让页面强制横屏(html)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>Demo</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <style type="text/css"> * { /*初始化样式*/ margin: 0; padding: 0; } html { /*用于 获取 屏幕的可视宽高*/ width: 100%; height: 100%; overflow: hidden; } body { /*让 body 初始 width 和 height 就 等于 页面可视区域的 宽高*/ position: fixed; left: 0; top: 0; width: 100%; height: 100%; /*用于 测试的 样式*/ background-color: #444; color: #FFF; letter-spacing: 4px; font-size: 28px; /*文字居中*/ display: flex; justify-content: center; align-items: center; } @media screen and (orientation:portrait) { /*竖屏样式*/ body { transform-origin: 0 0; transform: rotateZ(90deg) translateY(-100%); } } /*测试 边边角角*/ div { background-color: #F00; position: fixed; height: 2px; width: 100px; } div:nth-of-type(1){ top: 0; left: 0; } div:nth-of-type(2){ top: 0; right: 0; } div:nth-of-type(3){ bottom: 0; left: 0; } div:nth-of-type(4){ bottom: 0; right: 0; } </style> </head> <body> Loading2 <div></div> <div></div> <div></div> <div></div> <script> (function () { function resize() { var body = document.getElementsByTagName('body')[0]; var html = document.getElementsByTagName('html')[0]; var width = html.clientWidth; var height = html.clientHeight; var max = width > height ? width : height; var min = width > height ? height : width; body.style.width = max + "px"; body.style.height = min + "px"; } resize(); window.addEventListener("resize", resize) })(); </script> </body> </html>