在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:
将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。
当前回答
即使更改android的方向,onCreate方法仍会被调用。因此,将所有繁重的功能转移到这个方法并不会对您有所帮助
其他回答
谷歌推出的android架构中最好的组件之一将满足ViewModel的所有要求。
它旨在以生命周期的方式存储和管理与UI相关的数据,并允许数据在屏幕旋转时继续存在
class MyViewModel : ViewModel() {
请参阅:https://developer.android.com/topic/libraries/architecture/viewmodel
在清单的活动部分中,添加:
android:configChanges="keyboardHidden|orientation"
我所做的。。。
在清单的活动部分中,添加了:
android:configChanges="keyboardHidden|orientation"
在活动代码中,实现:
//used in onCreate() and onConfigurationChanged() to set up the UI elements
public void InitializeUI()
{
//get views from ID's
this.textViewHeaderMainMessage = (TextView) this.findViewById(R.id.TextViewHeaderMainMessage);
//etc... hook up click listeners, whatever you need from the Views
}
//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InitializeUI();
}
//this is called when the screen rotates.
// (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
InitializeUI();
}
将此代码添加到manifest.xml中。
这是你的活动。
<activity
....
..
android:configChanges="orientation|screenSize"/>
注意:如果将来有人和我面临同样的问题,我会发布这个答案。对我来说,下面这行是不够的:
android:configChanges="orientation"
当我旋转屏幕时,没有调用方法`onConfigurationChanged(配置新配置)。
解决方案:即使问题与方向有关,我也必须添加“screenSize”。因此,在AndroidManifest.xml文件中,添加以下内容:
android:configChanges="keyboardHidden|orientation|screenSize"
然后实现方法onConfigurationChanged(Configuration newConfig)