这是我尝试过的,它有效。 在res / values中作为bool.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="portrait_only">true</bool>
</resources>
在res / values-sw600dp和res / values-xlarge中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="portrait_only">false</bool>
</resources>
在我的活动的onCreate方法中:
if(getResources().getBoolean(R.bool.portrait_only)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
除了检查每个oncreate方法之外,还有其他一些方法可以做到这一点,完全相同的结果
答案 0 :(得分:1)
要么为
这样的活动创建基类//extending this to all of your activities isnt really that expensive
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getResources().getBoolean(R.bool.portrait_only)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
...
OR
在您的Application
类注册生命周期回调
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
if(getResources().getBoolean(R.bool.portrait_only)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Log.i(TAG , "ApplicationClass-OnActivityCreated()");
}
@Override
public void onActivityStarted(Activity activity) {
Log.i(TAG , "ApplicationClass-OnActivityStarted()");
}
@Override
public void onActivityResumed(Activity activity) {
Log.i(TAG , "ApplicationClass-OnActivityResumed()");
}
@Override
public void onActivityPaused(Activity activity) {
Log.i(TAG , "ApplicationClass-OnActivityPaused()");
}
@Override
public void onActivityStopped(Activity activity) {
Log.i(TAG , "ApplicationClass-OnActivityStopped()");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
Log.i(TAG , "ApplicationClass-OnActivitySaveInstanceState()");
}
@Override
public void onActivityDestroyed(Activity activity) {
Log.i(TAG , "ApplicationClass-OnActivityDestroyed()");
}
});
}
}
但我仍然更喜欢基类实现。
希望有所帮助:)