Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

android - Get data back from a fragment dialog - best practices?

I'm converting some of my project to use fragments. How do we communicate with a fragment dialog? I want to create a fragment dialog just to get some text input from the user. When the dialog is dismissed, I'd like to pass the entered text back to the "parent" fragment (the one that started it). Example:

public class MyFragment extends Fragment {

    public void onBtnClick() {
        // What's a good way to get data back from this dialog 
        // once it's dismissed?
        DialogFragment dlgFrag = MyFragmentDialog.newInstance();
        dlgFrag.show(getFragmentManager(), "dialog"); 
    }
}

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As eternalmatt said the given solution does not really answer the question. The way to communicate the dialog with the fragment is calling:

dialog.setTargetFragment(myCallingFragment, requestCode);

The way I do this is by creating the FragmentDialog with an static method where the listener is instanciated an then do the setFragmentTarget() stuff:

public mySuperFragmentDialog extends DialogFragment {
  public interface SuperListener{
     void onSomethingHappened();
  }

  public static mySuperFragmentDialog newInstance(SuperListener listener){
     MySuperFagmentDialog f = new MySuperFragmentDialog();
     f.setTargetFragment((Fragment) listener, /*requestCode*/ 1234);
     return f;
  }
}

To create the dialog from the fragment just do as usual:

Dialog dialog = MySuperFragmentDialog.newInstance(parentFragment);
dialog.show();

Then when you want to comunicate with the fragment which calls the dialog just:

Fragment parentFragment = getTargetFragment();
((SuperListener) parentFragment).onSomethingHappened();

This solution works only when dialog is gonna be created from Fragments and not from Activities, but you can combine both methods ('setFragmentTarget()' and the 'onAttach()' one) plus some Class checks to provide a full solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...