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
950 views
in Technique[技术] by (71.8m points)

android - Receiving data from a DialogFragment if you're calling from an Activity vs a Fragment?

I call my DialogFragment like so:

If I am in an Activity:

MyDialogFragment dialogfragment = new MyDialogFragment();
dialogfragment.show(getFragmentManager(), "");

If I am already in a Fragment:

MyDialogFragment dialogfragment = new MyDialogFragment();
dialogfragment.show(getActivity().getFragmentManager(), "");

In MyDialogFragment, which inflates an XML and allows the user to input some values to EditTexts and so forth, I want to be able to return those values back to wherever I called the dialog from.

For the sake of the question let's say my dialog class wants to return some private variables String mName and int mValue.

Is there a proper way to do this without knowing where the dialog is being called from (either an Activity or a Fragment)? How do I pass the values back / how do I receive them?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Create a callback interface and have pass it into your dialogfragment

interface DialogValuesCallback {
   void callThisFunctionWhenUserClicksOnOkInDialog(String passinmName,int passinmValue);
}

You can have your Activity or Fragment implement this interface.

Have a constructor in your MyDialogFragment which accepts the interface and assigns it to an member variable.

MyDialogFragment(DialogValuesCallback activityOrFragmentWhichImplementsThis){
    mInterfaceCallbackObjectRef = activityOrFragmentWhichImplementsThis;
}

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

...