Search code examples
androidbuttononclicklistener

Android Studio Button onClick Listener won't work


So I've been trying to implement a Button on my "RegisterActivity" that switches to another "LoginActivity". AndroidStudio offers this really nice Manager where I can just make a Button react to a written method.

onClick-Button onClick-Button

Why doesn't my Button react?

If I'm using this code snippet, the Button works, even if I don't add the method to the Button's onClick attribute:

Button signUpButton = (Button) findViewById(R.id.signUpButton);
    signUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RegisterActivity.this.switchToLoginPage();
        }
    });

public void switchToLoginPage() {
    Intent goToLoginPage = new Intent(getApplicationContext(), LoginActivity.class);
    startActivity(goToLoginPage);
}

But if I'm using this one, also adding the method to the Button's onClick attribute, he won't work:

    public void switchToLoginActivity(View view) {
        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}

I even checked the .xml files double and thrice:

<Button
        android:id="@+id/signUpButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="switchToLoginActivity"
        android:text="@string/sign_up_button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/passwordTextField"
        app:layout_constraintVertical_bias="0.5" />

Can anyone help?


Solution

  • You are setting onClick listener for signUpButton two times, one in java code:

    signUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RegisterActivity.this.switchToLoginPage();
        }
    });
    

    And also in XML:

    android:onClick="switchToLoginActivity"
    

    When you do that in XML, the switchToLoginActivity method is called when you click the button.

    You should either remove the clickListener which you are setting through setOnClickListener in java code, or remove android:onClick="switchToLoginActivity" and the switchToLoginActivity method.