带有MVVM的Android自定义对话框 [英] Android custom dialog with MVVM

查看:743
本文介绍了带有MVVM的Android自定义对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建自定义对话框,我希望当用户单击添加按钮时去调用改造并观察更改,但是我不知道如何将生命周期所有者传递给观察者

I am creating custom dialog and i want when the user click add button go and call retrofit and observe on changes but i don't know how to pass lifecycleowner to the observer

 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);
                }
            }
});

预先感谢

推荐答案

尝试此解决方案.它为我工作.

Try this solution. It worked for me.

从调用对话框的位置创建活动字段,并将其传递给生命周期所有者

Create a field of your activity from where you are calling the dialog and pass this in place of 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的示例.

You can refer the example of mvvm here if you want

这篇关于带有MVVM的Android自定义对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆