问题
I am working on an app and I am using a custom dialog which extends DialogFragment. This dialog will contain certain field that I want to pass to the parent activity. I tried implementing OnDismissListener but the parameter is a Dialog Interface.
Any Idea?
parent Activity:
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BreakCreator mDialog = new BreakCreator();
mDialog.show(getSupportFragmentManager(), "start break Creator");
}
});
listener:
@Override
public void onDismiss(DialogInterface dialog) {
Log.d("debug", "in onDismiss");
BreakCreator mBreakCreator = BreakCreator.class.cast(dialog);// This MIGHT not work
//TODO cast and shit
if(!mBreakCreator.isCancelled() ){
int startMinute = mBreakCreator.getStartMinute();
int startHour = mBreakCreator.getStartHour();
int endMinute = mBreakCreator.getEndMinute();
int endHour = mBreakCreator.getEndHour();
String day = mBreakCreator.getDay();
Break mBreak = new Break(new ultramirinc.champs_mood.Time(startHour, startMinute),
new ultramirinc.champs_mood.Time(endHour, endMinute), day);
breakList.add(mBreak);
Log.d("created", "break added");
recyclerView.invalidate();
}else{
Log.d("debug", "is not cancelled");
}
}
Dialog Class:
public void onDismiss(final DialogInterface dialog) {
super.onDismiss(dialog);
final Activity activity = getActivity();
if (activity instanceof DialogInterface.OnDismissListener) {
((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
}
}
回答1:
Use a custom listener, below is an example on how this could be implemented. This is also explained in the Android Developer Guide.
public class CustomDialog extends DialogFragment {
public interface CustomListener{
void onMyCustomAction(CustomObject co);
}
private CustomListener mListener;
public void setMyCustomListener(CustomListener listener){
mListener = listener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
Code to create dialog
...
}
@Override
public void onDismiss(DialogInterface dialog) {
if(mListener != null){
CustomObject o = new CustomObject();
mListener.onMyCustomAction(o);
}
super.onDismiss();
}
}
And when the custom dialog is created, set the listener.
CustomDialog awesomeDialog = new CustomDialog();
awesomeDialog.setMyCustomListener(new CustomDialog.CustomListener() {
@Override
public void onMyCustomAction(CustomObject o){
Log.i("TAG",o.toString());
}
});
来源:https://stackoverflow.com/questions/43400273/getting-information-from-dialogfragment-using-ondismiss