Java 在android运行时更改所有屏幕的方向
用例:我正在平板电脑和安卓电视上开发安卓应用程序,每个屏幕上都有“旋转屏幕”选项。我的问题是,如果用户点击旋转屏幕选项,我想在整个应用程序中更改屏幕方向。i、 e.所有屏幕应将其默认设置更改为选择的屏幕方向 我可以为您的需要提供一种方法:Java 在android运行时更改所有屏幕的方向,java,android,kotlin,screen-orientation,Java,Android,Kotlin,Screen Orientation,用例:我正在平板电脑和安卓电视上开发安卓应用程序,每个屏幕上都有“旋转屏幕”选项。我的问题是,如果用户点击旋转屏幕选项,我想在整个应用程序中更改屏幕方向。i、 e.所有屏幕应将其默认设置更改为选择的屏幕方向 我可以为您的需要提供一种方法: Hold the flag to change the orientation and verify it at onCreate(); and change it. @Override protected void onCreate(Bundle
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);
}
android:configChanges=“orientation”
onConfigurationChanged(Configuration new)
覆盖活动中的onConfiguration Changed()
回调onConfigurationChanged(configurationnewconfig)
中获得新的配置对象作为参数。集中存储,以便所有应用程序都可以访问它配置
值,如果该值为空(与初始值一样),则可以根据应用程序的需要在默认值
中启动
@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);
}
我希望这将帮助您单击旋转屏幕选项设置变量值。在每个活动的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);
}
}
但请确保在应用程序中的所有活动中都这样做。您可能需要重新启动应用程序才能生效。谢谢您的回复,您能分享OnConfiguration Changed()的代码吗method@binaryakash我已经添加了
onConfigurationChanged()
方法的示例代码,请检查,如果有帮助,请接受我的回答