skip to Main Content

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

enter image description here

2

Answers


  1. You can ignore the graying out – this is Studio’s way of telling you this bit of code is unnecessary and can be replaced with a shorter code.

    If you hover the mouse cursor on the grayed-out area you will see the Studio suggests that you use a Lambda instead.

    enter image description here

    Lambdas are just a shorthand way of writing methods. For example, Lambda version of onClickListener translates to this code.

    enter image description here

    You can either choose to go with the lambda suggestion or leave the code as-is – either way the code will run.

    Login or Signup to reply.
  2. 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
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search