我尝试使用此代码来防止在ImageView中多次单击,但这无济于事.
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;
}
}
在日志猫中,当我尽快单击ImageView 5次时,可以看到5行“按钮单击”.我可以看到log cat打印第一行,等待一会儿(2秒),然后打印下一行.我想当我单击ImageView时,触发的事件将按顺序移到队列中,不是吗?那么我该如何阻止呢?
我也尝试使用setEnable()或setClickable()代替isClicked变量,但是它也不起作用.
解决方法:
只需尝试此工作代码
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?
//我提到了这个androidlink.您可以更有效地处理线程,但是我希望下面的代码对您有用.
//您尝试这个
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;
}
}