简体   繁体   中英

How to interact with 2 dialog fragment lifecycle on Android?

I'm very new to Android development. I have gone through many android tutorials and articles but I'm still a little bit confusing about my situation right now.

What I need to do: I have two dialog fragment, f1 and f2. There is an audio playing in background. when any dialog pops up, stop playing audio, when dialog dismiss, audio resumes.

What I have done: I have implemented a listener interface with 2 methods: onCreateDialog and onDismissDialog . It worked for just one dialog (f1 or f2 pops up, and audio stops. Dialog dismisses, audio resumes)

What's not right: A situation that: f1 pops up, press "yes", f1 will dismiss, f2 will pop up. The audio will stop (actually it's already stop because f1 poped up), then the audio will resume. So I checked log, it seems that f2 onCreateDialog was called before f1 onDismissDialog , that's why audio resumed when f2 poped up.

Does anybody have any idea what I could do about this situation? ANY help is appreciated!!

Thanks a lot!!!

ArrayList <DialogFragment> dialogs = new ArrayList();

void resumeSound () {
    for (DialogFragment dialog: dialogs){
        //maybe isVisible won't work, try with isAdded() or add a custom     
        //flag like [boolean isVisible] inside the Dialog
        if (dialog.isVisible() {
           return;
        }
    }
    ....
    //Code to resume sound;
    ....
}
//Put following on each dialog fragment
onCreateDialog () {
    //Make sure dialog is added with a TAG or id, so you can find it later  
    dialogs.add(this);
}

onDismissDialog () {
    //you'll have to put following line inside an array iterator, 
    //check if TAG or id equals, and then remove 
    //(maybe also implement equals() for DialogFragment 
    dialogs.remove();
    resumeSound();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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