Disable OnClickListener Android
Solution 1
If skipsAllowed == 0
unregister onClickListener
See Remove an onclick listener
By the way, you should review your code, we usually set a click listener only once.
Solution 2
Simple: skipButton.setOnClickListener(null)
Solution 3
You are getting an exception because you are passing null context to loadAnimation
.
You can get application context with :
getApplicationContext()
And after animation start you should set you button to INVISIBLE to completely hide the skip button.
Animation skipFadeOut = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out);
skipButton.startAnimation(skipFadeOut);
skipButton.setVisibility(View.INVISIBLE);
Phoenix
Updated on June 05, 2022Comments
-
Phoenix almost 2 years
I have an
OnClickListener
on an image in my app. It allows the user to skip to a different part of the app if desired. The way the app runs, they can only use it 3 times.My issue is, I want to get fancy pants. So I added an
R.anim.fade_out
animation to make the image fade out after all 3 times were used. I am using a counter decreased by one in another method.The issue is, when the original method is recalled, it throws a
Null Reference Exception
because it can't find the image to set theOnClickListener
. I tried wrapping it in anIf/Else If
statement:if(skipsAllowed > 0){ skipButton.setOnClickListener(new OnClickListener(){ public void onClick(View v){ if(skipsAllowed > 0){ try { skippedPage(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); }else if(skipsAllowed == 0){ skipFadeOut = AnimationUtils.loadAnimation(null, android.R.anim.fade_out); skipButton.startAnimation(skipFadeOut); }
This still didn't work. Any ideas on how to stop this?
I instantiate the
ImageView
at the start of every new call to thisActivity
, should I be placing that inside my If/Else If? -
Phoenix almost 11 yearsThanks for the link, that helped. You were right, I moved my click listener up to the
onCreate()
, and simply unregistered it when it was time. Thanks again! -
Phoenix almost 11 yearsThanks! I actually saw that right after posting, I should have edited the question. It all works like it should.