检测是否重新开始活动,因为方向变化方向

2023-09-06 10:45:13 作者:◎仲夏冰桐◎

我如何可以检测,如果用户更改设备方向,所以我不每次活动时间重新运行相同的初始化code?要不我怎么能恢复我的活动状态(包括变量值)?

How can I detect if the user changed the device orientation so I don't run the same initialization code every time the activity is recreated? Or how can I restore my activity state (including variables values)?

感谢

推荐答案

推荐的方法是使用的 onSavedInstanceState()。这将节省您的活动状态和变量。

The recommended way is to use onSavedInstanceState(). This will save the state of your Activity and variables.

我通常做,据说是在文档的最后手段的方法,是处理配置改变自己。在清单你可以声明

The way I typically do it, and is said to be a last resort in the docs, is to handle the configuration change yourself. In the manifest you can declare

<activity
    ...
     android:configChanges="orientation"/>

然后在活动

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // add logic here if you need
}
 
精彩推荐