MVVM startActivityForResult

时间:2018-04-13 10:29:24

标签: android mvvm

单击视图时,应调用startActivityForResult。 但我不能在viewModel中调用startActivityForResult。我怎样才能实现它?

1 个答案:

答案 0 :(得分:3)

我在这里阅读了谷歌示例(https://github.com/googlesamples/android-architecture/tree/todo-mvvm-databinding)并找到解决方案:

  1. 创建一个实现的接口:

    public interface TaskItemNavigator {
        void openTaskDetails(String taskId);
    }
    
  2. 在视图模型中有一个弱引用:

    @Nullable
    private WeakReference<TaskItemNavigator> mNavigator;
    
  3. 在活动中实施:

    public class TasksActivity extends AppCompatActivity implements TaskItemNavigator{
        ...
        @Override
        public void openTaskDetails(String taskId) {
            Intent intent = new Intent(this, TaskDetailActivity.class);
            intent.putExtra(TaskDetailActivity.EXTRA_TASK_ID, taskId);
            startActivityForResult(intent, AddEditTaskActivity.REQUEST_CODE);
        }
    }