Domanda

I'm trying to use an interface to return data from a DialogFragment to the ArrayAdapter from which it's shown.

I've read something similar here, but I don't know how to call in the DialogFragment the function returning the data.

Anybody can help?

MyDialog.java

public class MyDialog extends DialogFragment {  

    static interface Listener {
        void returnData(int result);
    }

    /* ... */

    @Override
    public void onActivityCreated (Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);        

        mBtnSubmit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                // How can I call PCListAdapter.returnData ?

                dismiss();              
            }
        });
    }

}

PCListAdapter.java

public class PCListAdapter extends ArrayAdapter<PC> implements MyDialog.Listener {

    /* ... */

    public void showCommentDialog() {

        FragmentManager fm = ((Activity)mContext).getFragmentManager();
        MyDialog dialog = new MyDialog();
        dialog.show(fm, "mydialog");
    }

    @Override
    public void returnData(int result) {
    }
}
È stato utile?

Soluzione

The link you have read talks about communicating the Fragment with the Activity (using Listeners). This is done because the Fragment is tightly coupled to the Activity. Now in your case since you are using Adapter to launch a Fragment, this is you could probably do.

public class MyDialog extends DialogFragment {  

private Listener mListener;

public void setListener(Listener listener) {
  mListener = listener;  
}

static interface Listener {
    void returnData(int result);
}

/* ... */

@Override
public void onActivityCreated (Bundle savedInstanceState){
    super.onActivityCreated(savedInstanceState);        

    mBtnSubmit.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mListener != null) {
                 mListener.returnData(data);
            }

            dismiss();              
        }
    });
}
}

and for Adapter,

public class PCListAdapter extends ArrayAdapter<PC> implements MyDialog.Listener {

/* ... */

public void showCommentDialog() {

    FragmentManager fm = ((Activity)mContext).getFragmentManager();
    MyDialog dialog = new MyDialog();
    dialog.setListener(PCListAdapter.this);
    dialog.show(fm, "mydialog");
}

@Override
public void returnData(int result) {
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top