Communication between Fragment and DialogFragment

为君一笑 提交于 2019-12-18 12:15:10

问题


I'm trying to make a Fragment to show a Dialog using DialogFragment API.

My dialog only has an EditText view and I want to pass the string wrote on it back to the Fragment.

I'm able to show the dialog from the Fragment, but I'm not able to retrieve the string from the input field back to my Fragment.

I tried both ways to create a dialog: overwriting the DialogFragment.onCreateView method and writing the entire dialog's view and overwriting the DialogFragment.onCreateDialog and using the AlertDialog.Builder to make it easier to write the buttons behavior.

The Android documentation about dialogs passing events back to dialog's host is about host being always an Activity and never a Fragment. I tried to generalize the behavior for use it on my case, but I cannot.

I tried using the DialogFragment.onAttach callback to get the Activity reference and use an interface between the Fragment and the DialogFrament and it works fine, but I cannot retrieve the Fragment from the Activity to make it work.

Can anybody help with a brief example?

Thanks in advance


回答1:


You can use the setTargetFragment and getTargetFragment methods of Fragment. You can set your Fragment as the target of the DialogFragment and then retrieve a reference to it from within the DialogFragment.




回答2:


you can use callbacks. just implement a "done" button or something like that in your dialogfragment.

so in your dialogfragment do something like this:

protected OnDialogClickedListener callback = null;

public interface OnDialogClickedListener {
    public abstract void onDialogClicked(int position);
}

public void setOnDialogClickedListener(OnDialogClickedListener l){
    callback = l;
}

button.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        callback.onDialogClicked(position);
        dismiss();
    }
});

in your activity do something like this:

final YourFragment f = YourFragment .newInstance(0);
f.show(ft, "YourFragment ");
f.setOnDialogClickedListener(new OnDialogClickedListener() {
    @Override
    public void onDialogClicked(int position) {
        updateText(position);
        f.dismiss();
    }
});


来源:https://stackoverflow.com/questions/14026492/communication-between-fragment-and-dialogfragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!