Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 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 Reply

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...