Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid multi-click in image view android

I try to use this code to prevent multi-click in ImageView but it doesn't help.

    Boolean isClicked = false;
    @Override
    public void onClick(View v)
    {
        if (v == imgClick && !isClicked)
        {
                      //lock the image
            isClicked = true;
            Log.d(TAG, "button click");

            try
            {
                //I try to do some thing and then release the image view
                Thread.sleep(2000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            isClicked = false;
        }

    }

In the log cat, I can see 5 lines "button click" when I click on ImageView for 5 times as quickly as possible. I can see the log cat print the first line, wait for a while (2 seconds) and then print the next line.
I think when I click the ImageView, the fired event is moved to queue in order, isn't it?. So how can I stop that?
I also try to use setEnable() or setClickable() instead of isClicked variable but it doesn't work too.

like image 957
ductran Avatar asked Mar 29 '26 16:03

ductran


1 Answers

Just try this working code

    Boolean canClick = true; //make global variable
   Handler  myHandler = new Handler();

@Override
public void onClick(View v)
{
    if (canClick)
    {

       canClick= false;   //lock the image
       myHandler.postDelayed(mMyRunnable, 2000);

       //perform  your action here

    }

}

/* give some delay..*/
    private Runnable mMyRunnable = new Runnable()
    {
        @Override
        public void run()
        {   

         canClick = true;
         myHandler.removeMessages(0);
        }
     };


Instead of sleeping in 2 seconds, I use some task like doSomeThing() method (has accessed UI thread), and I don't know when it completed. So how can I try your way?

//I referred this android link. You can handle thread more efficiently but i hope below code will work for you.. //you try this and

 Boolean canClick = true; //make global variable
public void onClick(View v) {
        if(canClick){

          new DownloadImageTask().execute();
        }
    }

        private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {


            protected Bitmap doInBackground(String... urls) {
                 Log.d("MSG","Clicked");
                 canClick =false;
                 //perform your long operation here

                return null;
             }

             protected void onPostExecute(Bitmap result) {
                 canClick =true;
             }
         }
like image 141
vnshetty Avatar answered Apr 01 '26 05:04

vnshetty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!