어떤 버튼을 클릭했을 때 다른 화면으로 이동해야하는 경우가 있다. 처음에는 activity에서 강제로 listener를 걸어줬는데, 아무래도 이건 아니다 싶어서 찾아보니 activity와 뷰모델을 연결하는 interface를 하나 두는 거였더라.
액티비티에서 호출해줘야하는 메소드들을 적어놓는다.
public interface CallAnotherActivityNavigator { void callActivity(); }
뷰모델에서는 내비게이터의 메소드를 호출한다.
public class CallAnotherActivityModel implements BaseViewModel { private CallAnotherActivityNavigator navigator; public CallAnotherActivityModel(CallAnotherActivityNavigator navigator) { this.navigator = navigator; } @Override public void onCreate() {} @Override public void onResume() {} @Override public void onPause() {} @Override public void onDestroy() {} public void callActivity() { navigator.callActivity(); } }
레이아웃에서는 평소처럼 뷰모델의 메소드를 호출한다.
<layout> <data> <variable name="model" type="kr.susemi99.testmvvm.call_another_activity.CallAnotherActivityModel"/> </data> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="@{() -> model.callActivity()}" android:text="call"/> </LinearLayout> </layout>
실제 호출은 activity에서 하면 된다. 이러면 뷰모델은 정말로 뷰와 관련된 작업만 처리할 수 있다.
public class CallAnotherActivity extends AppCompatActivity implements CallAnotherActivityNavigator { private ActivityCallAnotherBinding binding; private CallAnotherActivityModel model = new CallAnotherActivityModel(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_call_another); binding.setModel(model); } @Override public void callActivity() { startActivity(new Intent(getApplicationContext(), InputActivity.class)); } }