I have a listFragment, where I want to display a DialogFragment (Yes/No) on listItemClick. I want to get back the user selection(Yes/No) in listFragment. I have read about the listener interface mechanism but that work with activity<->fragment. One way of doing this can be:
But do we have any simple mechanism for this simple task? any example or code?
There is another way how to get the result back from DialogFragment.
You can use Fragment.setTargetFragment(). When creating an instance of your DialogFragment set target fragment to it. Then in DialogFragment you can get this fragment from Fragment.getTargetFragment().
For example, you can do it so:
public interface DialogClickListener {
public void onYesClick();
public void onNoClick();
}
public class MyListFragment extends ListFragment implements DialogClickListener {
...
private void showDialog() {
DialogFragment dialog = new MyDialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(getFragmentManager(), "dialog");
}
@Override
public void onYesClick() {
// do something
}
@Override
public void onNoClick() {
// do something
}
}
public class MyDialogFragment extends DialogFragment {
private DialogClickListener callback;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
callback = (DialogClickListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement DialogClickListener interface");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("message")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
callback.onYesClick();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
callback.onNoClick();
}
});
return builder.create();
}
}
You can also use an event bus to facilitate the communication between components. Otto is a great library to use available here --> https://github.com/square/otto . It is made by the Square guys so you know its a quality open source project.
They have a sample in the repository that shows you how easy it is to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With