【问题标题】:How to disable landscape on small screens layout如何在小屏幕布局上禁用横向
【发布时间】:2014-02-14 00:55:03
【问题描述】:
我允许我的应用程序在 纵向和横向 (small-normal-large-xlarge) 的所有可能方向,但在小屏幕上对其进行测试后,我只是不喜欢看起来是这样,我想要做的是禁用小布局的横向。有没有办法做到这一点 ?
我发现的只是清单文件上的更改,但我相信通过重新配置清单我会将更改应用到所有布局。
【问题讨论】:
标签:
java
android
layout
landscape
【解决方案1】:
最简单的方法是将它放在所有活动的onCreate() 方法中(更好的是,将它放在 BaseActivity 类中并从中扩展所有活动)
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (isLargeDevice(getBaseContext())) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
} else {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
您可以使用此方法来检测设备是手机还是平板电脑:
private boolean isLargeDevice(Context context) {
int screenLayout = context.getResources().getConfiguration().screenLayout;
screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;
switch (screenLayout) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
return false;
case Configuration.SCREENLAYOUT_SIZE_LARGE:
case Configuration.SCREENLAYOUT_SIZE_XLARGE:
return true;
default:
return false;
}
}
【解决方案2】:
您可以像这样以编程方式handle runtime configuration changes
在您的清单中:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
在你的活动中
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
///check the screen size and change it to potrait
}
}
或查看this answer 了解如何查看屏幕尺寸并进行更改
【解决方案3】:
例如480屏幕尺寸设备:在oncreate方法中应用:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
if(width==480){
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}