I want to implement MVVM pattern using data-binding in my app. Here's the login button from my layout file:
<Button
android:id="@+id/login"
android:layout_width="0dp"
android:layout_height="50dp"
android:text="@{mainViewModel.name}"
android:textColor="@color/white"
android:onClick="@{mainViewModel.startNewActivity}"/>
The logic is, on clicking this login button, a new activity should be started. I'm a beginner in android, and my question is should I keep the startActivity part in my MainActivity or in my ViewModel class? (If I want it to be in accordance with the MVVM pattern)
If it should be in the mainActivity, I would replace the last line with
android:onClick="startNewActivity"
and then define the method in my MainActivity.
But, if it is to be placed in the ViewModel class, declaring the following method:
public void startNewActivity(View view) {
Intent login = new Intent(MainActivity.class, LoginActivity.class);
startActivity(login);
}
is giving error:
Cannot resolve constructor 'Intent(java.lang.Class<package.name.MainActivity>,java.lang.Class<package.name.LoginActivity>)'
How do I start the LoginActivity from my ViewModel class then?
change like below.
If you want to start LoginActivity from MainActivity then you have to pass this class in intent on button click event. like this,
MainViewModel
MainActivity.java
LoginActivity.java
activity_main.xml
first argument of
Intent
will be context, not class. Replace your first argument withMainActivity.this
First create new activity(MainActivity).check the following code.
create another activity(LoginActivity). LoginActivity.java
activity_main.xml
AndroidManifest.xml
Well you cannot start Activity from a custom class eg: Employee. All you can do is change the Architecture of your application so that you can start an Activity on some button click in the
MainActivity
.and then to start
where
MainActivity.this
is the context andLoginActivity.class
is that Activity to be started.