Search code examples
javaandroidandroid-studiobuttononclicklistener

My onclicklistener is grayed out and it's not taking me to defined target


My onclicklistener is grayed out and it's not taking me to defined target. How can I solve this?

enter image description here


Solution

  • Recently the part new View.OnClickListener() will be marked gray because the compiler is suggesting a shorthand way of simplifying your code and this is called lambda.

    So instead of this View.OnClickListener(), you will now have v->{} where v is view (you can change the latter v to any latter of your choice).

    To quickly fix this; Click on the gray part and se alt + Enter to get suggestion.

    Moreover,

    Setting onClickListener could be in two ways;

    1. Implementing onClickListener in your activity.
    2. Calling onClickListener directly from your button.

    For the first one;

    Your activity should implement onClickListener; Then in your onCreate method of your activity, reference the button and set this as context to the button onClick;

    yourButton1.setOnClickListener(this);
    yourButton2.setOnClickListener(this);
    yourButton3.setOnClickListener(this);
    

    button can be more than one.

    --> In your generated onClick method you can now use switch statement to check which button is clicked;

    For the second one For this make sure you reference your button correctly by importing the corresponding button you used in your xml layout.

    import android.widget.Button

    Reference your button from xml in your activity using R.id.buttonName

    Button yourButton = findViewById(R.id.yourButtonId);

    Now set onClickListener directly to the button;

    //without lambda
    yourButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Do whatever you want 
    
            }
        });
    
    
    //with lambda
    yourButton.setOnClickListener(v->{
    //Do whatever here
    });