AJJ
AJJ

Reputation: 2074

Invoking a method from parent fragment

Normally, from an Activity I could invoke an object that extends DialogFragment and implements DialogInterface.OnClickListener().

Then if I wanted to, from that Dialog, invoke a method in the parent activity, I could do ((NameOfParentActivity)getActivity()).nameOfMethod();

But now I am invoking such an object from a Fragment (specifically, a page of a ViewPager) instead of an Activity.

I'm not exactly sure what to change to get the method-calling line to work. In other words I am trying to call a method from the Fragment class, while inside its DialogFragment object.

Edit: OnClick() code from my Adapter class:

public void onClick(View v) {
    DeleteGameBoardDialogFragment dialogFragment = new DeleteGameBoardDialogFragment();
    Bundle args = new Bundle();
    args.putString(TabFragmentGameBoard.GAMEBOARD_DIALOG_TAG, mGameBoards.get(position).getGameBoardName());
    dialogFragment.setArguments(args);
    dialogFragment.show(((Activity) mContext).getFragmentManager(), "");
}

Upvotes: 4

Views: 3476

Answers (2)

Bharatesh
Bharatesh

Reputation: 9009

You can solve your issue with setTargetFragment() and getParentFragment() to your dialog Fragment.

Call dialog from your ViewPager fragment, where you want execute a fragment method.

DeleteGameBoardDialogFragment dialogFragment = new DeleteGameBoardDialogFragment();
dialogFragment.setTargetFragment(this,1);
FragmentTransaction transaction=getChildFragmentManager().beginTransaction();//must be getChildFragmentManager()
dialogFragment.show(transaction, "df");

And inside of your DeleteGameBoardDialogFragment, call below code

DeleteGameBoardDialogFragment  fragment=(DeleteGameBoardDialogFragment) getParentFragment();
fragment.nameOfMethod()

IMPT: make sure you call dialog from a fragment only and not from activity. Why If you call from activity getParentFragment() returns null.

getParentFragment () : Returns the parent Fragment containing this Fragment. If this Fragment is attached directly to an Activity, returns null.. more visit SO : getParentFragment returning null

Upvotes: 3

ekouChiq
ekouChiq

Reputation: 254

From what I understood from your question, you have a ViewPager that opens a dialog when a button is clicked, and you wanted to access a method from your ViewPager Fragment?

If this is your question, might as well try making an Interface that behaves like a Listener and pass it on the DialogFragment. The Fragment where your method is, should implement this listener.

Upvotes: 0

Related Questions