先看這樣一個報錯:
Caused by: android.view.InflateException: Binary XML file line #13 in com.example.kotlindemo:layout/layout_dialog_simple: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #13: Duplicate id 0x7f080152, tag null, or parent id 0xffffffff with another fragment for com.example.kotlindemo.ui.fragment.SimpleFragment
錯位很明顯:不能重復(fù)加載同一個id或者tag的fragment进副。這就意味著:重復(fù)new 含有同一個Fragment的dialog就會報錯手幢。
接下來看這樣一個實例:
fun showSimpleDialog(view: View) {
if(!this::simpleDialog.isInitialized){
simpleDialog = SimpleDialog(this).apply {
setContentView(LayoutInflater.from(activity).inflate(R.layout.layout_dialog_simple, null))
}
}
simpleDialog.show()
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<fragment
android:id="@+id/simpleFragment"
android:name="com.example.kotlindemo.ui.fragment.SimpleFragment"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
fragment放進dialog中show:第一次
SimpleFragment: onAttach:
SimpleFragment: onCreate:
SimpleFragment: onStart:
SimpleFragment: onResume:
SimpleDialog: onCreate:
dimiss時:無日志
第二次show:無日志
因為此時一直處于onResume的狀態(tài)斜姥。
所以,fragment放進dialog中則無法正常使用生命周期回調(diào)方法了。但是在Activity其它生命周期發(fā)生變化的時候,此時的fragment的生命周期發(fā)生了對應(yīng)的同步變化。
也就是說:fragment放進dialog爽室,其生命周期是與Activity同步的。(即便是fragment直接放進Activity的布局頁面方式潘飘,其show和hide也是不會觸發(fā)生命周期變化的)
這一點從源碼也可以驗證:
/**
* Called when the Fragment is visible to the user. This is generally
* tied to {@link Activity#onStart() Activity.onStart} of the containing
* Activity's lifecycle.
*/
@CallSuper
public void onStart() {
mCalled = true;
}
/**
* Called when the fragment is visible to the user and actively running.
* This is generally
* tied to {@link Activity#onResume() Activity.onResume} of the containing
* Activity's lifecycle.
*/
@CallSuper
public void onResume() {
mCalled = true;
}
借助這種方式,可以實現(xiàn)dialog生命周期的感知掉缺。(當然dialog使用lifecycle也是可以做到的)