The use of Android Fragment in Dialog

First look at such an error:

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

The misplacement is obvious: fragments with the same id or tag cannot be loaded repeatedly. This means: repeated new dialogs containing the same Fragment will report an error.

Next look at such an example:

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>

The fragment is put into the dialog to show: the first time

SimpleFragment: onAttach:
SimpleFragment: onCreate:
SimpleFragment: onStart:
SimpleFragment: onResume:
SimpleDialog: onCreate:

When dimiss: no log
The second show: no log

Because it has been in the state of onResume at this time.
Therefore, if the fragment is put into the dialog, the life cycle callback method cannot be used normally. However, when other life cycles of the Activity change, the life cycle of the fragment at this time undergoes a corresponding synchronous change.

That is to say: the fragment is put into the dialog, and its life cycle is synchronized with the Activity. (Even if the fragment is directly placed into the layout page of the Activity, its show and hide will not trigger life cycle changes)

This can also be verified from the source code:

/**
 * 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;
}

In this way, the awareness of the dialog life cycle can be realized. (Of course, it is also possible to use lifecycle in dialog)

Guess you like

Origin blog.csdn.net/ganshenml/article/details/120276679