My onclicklistener is grayed out and it’s not taking me to defined target. How can I solve this?
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
My onclicklistener is grayed out and it’s not taking me to defined target. How can I solve this?
2
Answers
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.
Lambdas are just a shorthand way of writing methods. For example, Lambda version of onClickListener translates to this code.
You can either choose to go with the lambda suggestion or leave the code as-is – either way the code will run.
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;
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;
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;