Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data back from a fragment dialog - best practices?

Tags:

android

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

like image 382
user291701 Avatar asked Mar 19 '12 18:03

user291701


People also ask

How can we pass data from fragment to fragment?

Passing Data between fragments in Android using ViewModel: To actually pass the data between fragments, we need to create a ViewModel object with an activity scope of both the fragments, initialize the ViewModel , and set the value of the LiveData object.

How will you pass data from one fragment to another fragment in Android using interface?

To pass data from one fragment to another Bundle will help. LifeShapeDetailsFragment fragment = new LifeShapeDetailsFragment(); // object of next fragment Bundle bundle = new Bundle(); bundle. putInt("position", id); fragment. setArguments(bundle);


1 Answers

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.

like image 140
juanmeanwhile Avatar answered Oct 29 '22 15:10

juanmeanwhile