我尝试使用此代码来防止在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;
}
}
在log cat中,当我尽快点击ImageView 5次时,我可以看到5行“按钮点击”。我可以看到日志cat打印第一行,等待一会儿(2秒),然后打印下一行。我想当我点击ImageView时,被触发的事件按顺序移动到队列,不是吗?那我该怎么办呢?
我也尝试使用 setEnable()或 setClickable()而不是isClicked变量,但它也不起作用。
答案 0 :(得分:3)
试试这个工作代码
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 link。你可以更有效地处理线程,但我希望下面的代码可以为你工作.. //你试试这个和
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;
}
}
答案 1 :(得分:1)
您可以跟踪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线程等待并不是一个好主意。