Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call parent fragment method from dialog fragment

I have a parent fragment, within this. Upon a button click, a child dialog fragment is getting created. Now I would like to know how to call parent fragment function from child dialog fragment.

Here is the sample code :

/**SampleFragment.java**/

public class SampleFragment extends Fragment {
    // Instantiate view & add event handlers    

    public void onButtonClick(....) {
        // Create a dialog framgent
    }

    public void refreshView() {

    }
}

/**SampleDialogFragment.java**/

public class SampleDialogFragment extends DialogFragment {
    // Instantiate view for dialog

    public void onButtonClick(...) {
        // Call parent fragment method, i.e call refreshView() of SampleFragment 
    }
}
like image 648
Naruto Avatar asked Nov 08 '14 04:11

Naruto


2 Answers

In a Fragment:

SampleDialogFragment dialogFragment = new SampleDialogFragment();
dialogFragment.show(getChildFragmentManager());

In a DialogFragment:

((SampleFragment) getParentFragment()).refreshView();

After calling this method, you can access public methods of a parent fragment.

like image 130
Anant Shah Avatar answered Oct 19 '22 01:10

Anant Shah


In say your parent fragment, SettingsFragment for example. Note the setTargetFragment()

public void onButtonClick(....)
{
            PrefLanguageDialogFragment prefLang = PrefLanguageDialogFragment.newInstance();
            prefLang.setTargetFragment(SettingsFragment.this, 1337);
            prefLang.show(getFragmentManager(), "dialog");
}

In our dialog, note the getTargetFragment()

SettingsFragment frag = (SettingsFragment)getTargetFragment();
if(frag != null){
   frag.refreshSomething();
}
like image 38
SteD Avatar answered Oct 19 '22 03:10

SteD