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:
- Define interface in dialog fragment containing yes/no button selection functions, and call these methods on alert dialog positive/negative button clicks.
- Implement this interface in Main activity.
- Initiate dialogFragment in listFragment onItem click.
- Save user selection in activity.
- get this choice in listFragment by another interface, implemented in Main activity.
But do we have any simple mechanism for this simple task? any example or code?
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.
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: