![](/img/trans.png)
[英]onCreateView running twice after recreation of fragment after Orientation Change
[英]Fragment recreation on configuration change
我對os的配置更改處理有疑問,假設我在onCreate()中有一個Activity,它使用該片段中定義的特殊構造函數創建一個(或多個)片段實例。
當設備方向改變時,系統會破壞並再次創建片段,如果我是正確的,它將使用默認(無參數)構造函數來執行此操作,同時活動也將重新創建,它將再次使用相同的構造函數實例化片段。 我的問題是,內存中會有兩個不同的實例嗎? 如果沒有,他們如何解決並成為一個?
在活動的整個生命周期中保持片段狀態的責任在FragmentManager
,這就是為什么在提交片段事務時有commit
和commitAllowingStateLoss
的選項。 如果留給它自己的設備, Fragment
的狀態將自動恢復。 但是......如果你在代碼中添加片段(而不是在xml布局中添加它),那么只有在需要時才能添加它。
通常,在onCreate
的情況下,檢查活動是否未重新啟動就足夠了,即檢查savedInstanceState == null
然后再添加片段。
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
你的問題的答案:
內存中會有兩個不同的實例嗎?
是的,如果您只是在每次調用onCreate
添加片段,那么將會有多個實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.