1

When I press a button in my Activity, a DialogFragment pops up. Inside the dialog fragment, there is a RecyclerView that looks a like a normal list view.

The behaviour I want is that when I press on row n of the RecyclerView, the DialogFragment closes and the Activity does something based on the value associated with row n.

It seems that the ViewHolder has to implement the OnClickListener interface. When a row is clicked, the ViewHolder's delegate should do something. The delegate should be the DialogFragment. And the DialogFragment in turn talks with the Activity to which it is attached.

If this is the case, the ViewHolder has to ask the DialogFragment to do something, and the DialogFragment asks the Activity to do something. Is this the right approach? How do I pass the reference of the DialogFragment to onCreateViewHolder()? Should the Adapter keep a reference to the DialogFragment?

Jonas
  • 534
  • 8
  • 16
  • Please check: http://stackoverflow.com/questions/24885223/why-doesnt-recyclerview-have-onitemclicklistener-and-how-recyclerview-is-dif – sider Aug 09 '15 at 16:42
  • Thanks for the link. I've checked that. But my case is different in that the recycler view is inside a fragment and it needs to talk with the activity. I want to know if my approach is right. – Jonas Aug 09 '15 at 16:43
  • Try to work with interface, make an interface having one function onDialogItemClick, then implement it in activity and pass its reference to the adapter. Then call that method with that reference in adapter. And let your activity method do the work. – UMESH0492 Aug 09 '15 at 16:50

1 Answers1

2

Yes, you are moving in the right direction. Pass the DialogFragment's reference in the constructor of the adapter. Once you have the reference and the desired click event fires, call getActivity() on the dialog's reference to get a reference to the activity. Then you can do whatever you want in the activity. Also, I suggest you implement listeners using interfaces. What you want to do is keep the DialogFragment invisible to the underlying activity and your adapter loosely coupled to the DialogFragment, and interfaces will help in that case.

androholic
  • 3,633
  • 3
  • 22
  • 23
  • Thank you. Does it mean that in `onCreateDialog`, I pass in `this` to the `Adapter`'s constructor? – Jonas Aug 09 '15 at 16:54
  • That would be one way to do it. What you can also do is make your activity implement a listener interface, and pass your activity casted to the listener using ((Listener) getActivity()) instead of passing this (i.e the Dialog). That way you can directly call the activity from the adapter. – androholic Aug 09 '15 at 16:59
  • Thanks for the suggestion. It's always good to learn from alternatives. I think I will go for the pass-the-fragment approach, because in that way, the `DialogFragment` has a chance to close itself. – Jonas Aug 09 '15 at 17:09