Search code examples
javaandroidandroid-activityandroid-viewonclicklistener

Have to click a button twice for it to work in Android Studio


So I am currently creating an app and one of the small things that have been bothering me is the fact that I have to click a button twice for it to work.

This is my code and I can't see anything wrong with it:

public void signUpButtonClickAction(View v){
    Button signUpButtonClick = (Button) findViewById(R.id.signUpButton);
    signUpButtonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, Signup.class));
        }
    });
}

xml code for my button:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/signUps"
    android:id="@+id/signUpButton"
    android:layout_marginBottom="38dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="signUpButtonClickAction"/>

It is probably a small fix but even I can't spot this bug


Solution

  • Solution

    Remove the line android:onClick="signUpButtonClickAction" and add

    Button signUpButtonClick = (Button) findViewById(R.id.signUpButton);
    signUpButtonClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, Signup.class));
        }
    });
    

    to the onCreate method of your activity or the onCreateView method of your fragment.

    Alternative Solution

    Alternatively, change the code to this

    public void signUpButtonClickAction(View v) { 
        startActivity(new Intent(MainActivity.this, Signup.class));
    }
    

    Explanation

    The line android:onClick="signUpButtonClickAction" in the xml is causing an internal call to signUpButtonClick.setOnClickListener(), so you don't have to set up an onClickListener in the signUpButtonClickAction again.

    Initializing multiple buttons

    private void initializeButtons() {
        Button signUpButtonClick = (Button) findViewById(R.id.signUpButton);
        signUpButtonClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, Signup.class));
            }
        });
    
        Button anotherButton = (Button) findViewById(R.id.anotherButton);
        anotherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("TAG", "Clicked on another button!");
            }
        });
    }
    

    Now simply call initializeButtons() from the onCreate method of your activity.