用例:我正在平板电脑和Android TV中开发Android应用程序,每个屏幕都包含"旋转屏幕"选项。我的查询是,如果用户点击旋转屏幕选项,我想在整个应用程序中更改屏幕方向。即所有屏幕都应将其默认设置更改为选择的屏幕方向。
Hold the flag to change the orientation and verify it at onCreate(); and change it.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isLandScape)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
}
单击旋转屏幕选项时,设置变量值。在每个活动的onCreate((方法中检查此变量,并设置方向如下:-
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Check the value of variable in if condition
if (value.equals("landscape")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
但请确保对应用程序中的所有活动执行此操作。 您可能必须重新启动应用程序,效果也很好。
我可以给你一种方法来满足你的需要:
- 针对您的活动添加
android:configChanges = "orientation"
- 第 1 步将使您的活动在用户单击按钮时从 Android 系统获取回调
onConfigurationChanged(Configuration new)
Rotation
- 在活动中
Override
onConfigurationChanged()
回调 - 您将在
onConfigurationChanged(Configuration newConfig)
中获得新的配置对象作为参数。集中存储它,以便所有应用程序都可以访问它。 -
在所有活动中编写代码,首先检查集中存储的
configuration
值,如果为 null(最初(,则可以根据应用的需要以纵向或横向default
开头@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Make getCurrentConfig() method available centrally via Interface or Application level, depends on our logic if (getCurrentConfig() == LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else if (getCurrentConfig() == PORTRAIT) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } setContentView(R.layout.activity_main); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Store newConfig centrally, this object describes current configuration // For Example, if I have a singleton class which holds configuration related things, I can do following // ConfigurationManager = Singleton class managing configuration across app // getInstance() = method which will return singleton object of ConfigurationManager // setConfiguration(Configuration config) = setter method will be used to update configuration inside ConfigurationManager when configuration changes happen ConfigurationManager.getInstance().setConfiguration(newConfig); }
这样,您可以集中管理所有活动的当前轮换更改 我希望这对你有帮助