从ViewModel启动DialogFragment的推荐方法是什么?
我在 Recyclerview
中有一个列表对象。当长按一个项目时,我想显示一个对话框,其中包含点击该项目的数据。
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.
Recyclerview
是使用每个项目的数据绑定,我可以在长按时使用Log显示所选项目中的数据。
The Recyclerview
is using data binding for each item and I am able to display data from the selected item using Log when long-pressing.
但是,当您尝试显示对话框时,您需要进入活动
,不建议在 ViewModel
对象中使用。
When trying to show a dialog, however, you need to get to the Activity
, which is not recommended to use in the ViewModel
object.
那么如何显示对话框呢?
So how can I show the dialog?
谢谢,Ove
从概念上讲,一个ViewModel让我觉得从一个错误的地方发起一个Dialog。为了更清楚地做到这一点,我将RecyclerView.ViewHolder传递到布局中,并在ViewHolder上有一个方法,触发RecyclerView.Adapter上的自定义侦听器。然后,任何订阅该侦听器(Activity / Fragment)的人都可以启动Dialog。可能看起来有点迂回,但我不认为列表项的ViewModel应该知道或控制其环境。
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.
这是一个例子。这是使用数据绑定和ViewModel处理RecyclerView项目点击的一般模式。这不是一个完整的例子,只是突出显示这种特定模式的代码。
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
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<data>
<variable
name="viewHolder"
type="com.example.ViewHolder"
/>
<variable
name="viewModel"
type="com.example.ViewModel"
/>
</data>
<com.example.View
android:layout_width="match_parent"
android:layout_height="24dp"
android:onClick="@{() -> viewHolder.onClick(viewModel)}"
/>
</layout>
适配器:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public interface SelectionListener {
void onSelectionChanged(int newPosition, ViewModel viewModel);
}
private @NonNull WeakReference<SelectionListener> selectionListener =
new WeakReference<>(null);
public void setSelectionListener(@Nullable SelectionListener listener) {
selectionListener = new WeakReference<>(listener);
}
public class ViewHolder extends RecyclerView.ViewHolder<ViewBinding> {
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);
}
}
}
}