我允许所有可能的方向为我的应用程序的肖像和风景(小 - 正常 - 大 - xlarge)但在小屏幕上测试后,我只是不喜欢它是如何出现所以,我正在尝试do是禁用小布局的横向。有没有办法做到这一点 ?
我发现只是对清单文件进行了更改,但我相信通过重新配置清单,我会将更改应用于所有布局。
最简单的方法是将它放在所有活动的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;
}
}
检查此链接,您可以根据需要检查设备类型和设置方向
Android: allow portrait and landscape for tablets, but force portrait on phone?
你可以这样编程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以了解如何检查屏幕尺寸并进行更改
例如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);
}