与MVVM的Android自定义对话框

时间:2018-04-17 12:34:27

标签: android mvvm retrofit customdialog android-livedata

我正在创建自定义对话框,我想当用户点击添加按钮去调用改造并观察更改但我不知道如何将lifecycleowner传递给观察者

 private void observeViewModel(ProjectListViewModel viewModel) {
        // Update the list when the data changes
        viewModel.getProjectListObservable().observe( ***what to pass here ??*** , new Observer<List<Project>>() {
            @Override
            public void onChanged(@Nullable List<Project> projects) {
                if (projects != null) {
                    //…
                    projectAdapter.setProjectList(projects);
                }
            }
});

提前致谢

1 个答案:

答案 0 :(得分:1)

试试这个解决方案。它对我有用。

在您调用对话框的位置创建活动字段,并将其传递给lifecycleowner

public class YourDialog extends DialogFragment {

private YourActivity activity;

    public static YourDialog newInstance(YourActivity activity) {
        YourDialog dialog = new YourDialog();
        dialog.activity = activity;
        return dialog;
    }

    private void observeViewModel(ProjectListViewModel viewModel) {
    // Update the list when the data changes
    viewModel.getProjectListObservable().observe( activity , new Observer<List<Project>>() {
        @Override
        public void onChanged(@Nullable List<Project> projects) {
            if (projects != null) {
                //…
                projectAdapter.setProjectList(projects);
            }
        }
    });

}

如果需要,可以参考mvvm here的示例