简体   繁体   English

方向更改后,活动恢复了两次

[英]Activity was restored twice when the orientation changes

I am having some problems with an activity of my Android aplication. 我的Android应用程式活动发生问题。

I have discovered that my app enters twice in 'onCreateView()' method of this activity when orientation changes, and it is causing me problems. 我发现方向改变时,我的应用在此活动的“ onCreateView()”方法中输入了两次,这给我带来了问题。 When I click the corresponding button and this activity starts is all ok, but whithin this activity when the orientation changes I have some problems because enters twice, ie activity restarts twice ... 当我单击相应的按钮并且此活动开始时一切正常,但是当方向改变时,此活动出现一些问题,因为输入两次,即活动重新启动两次...

... Does anyone know the behaviour of an activity when orientation changes? ...当方向改变时,有人知道活动的行为吗? Why does this happen? 为什么会这样?

Thanks so much. 非常感谢。

Since onCreateView() is not part of the Activity lifecycle, but rather is part of the Fragment, I would assume you have a fragment somewhere in your activity. 由于onCreateView()不是Activity生命周期的一部分,而是Fragment的一部分,因此我假设您在Activity的某处有一个fragment。 Also I would assume you add this fragment manually using FragmentManager and FragmentTransaction . 我还要假设您使用FragmentManagerFragmentTransaction手动添加此片段。 Since Android keeps all the added fragments between orientation changes, it is quite possible that you don't check if your Fragment is already present in this activity, so you add it again which causes additional onCreateView to be called. 由于Android会将所有添加的片段保留在方向更改之间,因此很有可能不检查片段是否已存在于此活动中,因此您再次添加它会导致调用其他onCreateView

If this is the case - you need to check if your savedInstance is null within onCreate . 如果是这种情况,则需要检查onCreate内的savedInstance是否为null。 If it is - you add fragment. 如果是,则添加片段。 Otherwise activity is getting restored, so fragment is already there. 否则,活动将恢复,因此片段已经存在。

A lot of assumptions for the answer, I know. 我知道很多答案的假设。 But I'm still mastering my telepathy skills :) 但是我仍然在掌握我的心灵感应技巧:)

When orientation changes onDestroy() is called, followed by onCreate(). 方向更改时,将调用onDestroy(),然后调用onCreate()。 For more : http://developer.android.com/guide/topics/resources/runtime-changes.html 有关更多信息: http : //developer.android.com/guide/topics/resources/runtime-changes.html

Try to add this in AndroidMainfest.xml in your activity: 尝试在您的活动中将其添加到AndroidMainfest.xml中:

android:configChanges="orientation|screenSize|keyboardHidden"

This means not to recreate the activity when orientation changes. 这意味着在方向更改时不要重新创建活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM