I am applying MVVM pattern in native Android development. I have a LoginActivity and it will host two different fragments that are LoginFragment and RegisterFragment. I am not sure what to do in this case. A viewModel for the LoginActivity or two different ViewModel for two fragments. If I create one viewModel for activity, login and register view bindings and logics will mix up with each other. But in many tutorials developers are saying that we should create one viewmodel per activity and access those viewmodels from fragment. How should I handle things here?
My login fragment if necessary
public class LoginFragment extends Fragment {
private LoginViewModel loginViewModel;
public LoginFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentLoginBinding fragmentLoginBinding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_login);
loginViewModel = ViewModelProviders.of(this, new LoginViewModelFactory(getActivity().getApplication(),
LoginRepository.getInstance())).get(LoginViewModel.class);
fragmentLoginBinding.setViewModel(loginViewModel);
fragmentLoginBinding.executePendingBindings();
return inflater.inflate(R.layout.fragment_login, container, false);
}
}
and LoginActivity
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FragmentUtil.replaceFragment(getSupportFragmentManager(), R.id.entry_frame, new LoginFragment(), "login");
}
}