What is the recommended way to launch a DialogFragment from a ViewModel?

前端 未结 5 1529
感情败类
感情败类 2020-12-06 06:40

I have a list objects in a Recyclerview. When long-pressing an item I want to show a dialog with data from the item clicked.

The Recyclerview

5条回答
  •  醉酒成梦
    2020-12-06 07:20

    Conceptually a ViewModel strikes me as the wrong place to launch a Dialog from. To do it more cleanly I would pass the RecyclerView.ViewHolder into the layout, and have a method on the ViewHolder that triggers a custom listener on your RecyclerView.Adapter. Then whoever subscribes to that listener (Activity/Fragment) can launch the Dialog. May seem a little roundabout, but I don't think a ViewModel of a list item should have knowledge or control of its environment.

    Here is an example. This is a general pattern for handling RecyclerView item clicks with data binding and a ViewModel. This is not a complete example, just the code to highlight this specific pattern.

    Layout:

    
        
        
        
        
    
        
    
    

    Adapter:

    class MyAdapter extends RecyclerView.Adapter {
        public interface SelectionListener {
            void onSelectionChanged(int newPosition, ViewModel viewModel);
        }
    
        private @NonNull WeakReference selectionListener =
                new WeakReference<>(null);
    
        public void setSelectionListener(@Nullable SelectionListener listener) {
            selectionListener = new WeakReference<>(listener);
        }
    
        public class ViewHolder extends RecyclerView.ViewHolder {
            ViewHolder(ViewBinding binding) {
                super(binding.getRoot());
    
                binding.setViewHolder(this);
                binding.setViewModel(new ViewModel());
            }
    
            public void onClick(ViewModel viewModel) {
                SelectionListener listener = selectionListener.get();
                if (listener != null) {
                    listener.onSelectionChanged(getAdapterPosition(), viewModel);
                }
            }
        }
    }
    

提交回复
热议问题