0

I have a button to show a search bar in my activity and, after ten seconds, I hide the search bar, but if the user presses the button to hide the search bar before 10 seconds, the post-delay must restart or stop below the code used. how do i stop postdelayed?

 barraBrilho.setVisibility(View.GONE);

    brilho.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!gone) {

                Animation anim = AnimationUtils.loadAnimation(getActivity(),R.anim.translate_layout_right );
                barraBrilho.startAnimation(anim);
                barraBrilho.setVisibility(View.GONE);

                gone = true;
            }

    else{ barraBrilho.setVisibility(View.VISIBLE);
        Animation anim = AnimationUtils.loadAnimation(getActivity(),R.anim.translate_layout_left);
        barraBrilho.startAnimation(anim);
        gone = false;

                new Handler().postDelayed( new Runnable() {
                    @Override
                    public void run() {
                        Animation anim = AnimationUtils.loadAnimation( getActivity(), R.anim.translate_layout_right );
                        barraBrilho.startAnimation( anim );
                        barraBrilho.setVisibility( View.GONE );
                        gone = true;
                    }
                }, 10000 );

            }
        }
    } );

1 Answers1

0

Call handler.removeCallbacks(runnable) when user clicks the brilho button.

Handler handler = new Handler();
Runnable runnable = new Runnable();

handler.removeCallbacks(runnable);

I recommend you make a subclass of Runnable and refer Activity instance by WeakReference

class CustomRunnable extends Runnable {
     
     CustomRunnable(Activity activity) {
         this.weakAct = WeakReference(activity);
     }

     @Override
     public void run() {
         Activity act = weakAct.get();
         if (act != null) {
            // do your logic and Activity is been able to leak now
         }
     }
}
HunkD
  • 76
  • 2