Avoid repeatedly clicking on the android image

I am trying to use this code to prevent multiple clicks in ImageView, but this does not 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 log cat, I can see 5 lines of “click on a button” when I click on ImageView 5 times as fast as possible. I see the log cat print the first line, wait a while (2 seconds), and then print the next line.
I think that when I click ImageView, the fired event moves to the queue in order, right? So how can I stop this?
I am also trying to use setEnable () or setClickable () instead of the isClicked variable, but it does not work either.

+3
source share
2 answers

    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?

// android . , , . //

 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;
             }
         }
+3

View, , :

private long calcTime;
private boolean isClickedLately(final long millisToWait)
{
    if (System.currentTimeMillis() - calcTime < millisToWait)
        return true;
    return false;
}

@Override
public void onClick(View v)
{
    if (isClickedLately(2000))
        return;
    calcTime = System.currentTimeMillis();
    Log.d(TAG, "consuming button click");
    // perform the necessary actions
}

millisToWait "", , 2 , .

, Threads, , , gui .

+1

All Articles