android locking eventListener and even handling
I have a simple button onClickListener in my android application, and all it does is write some stuff to the database. It looks somet开发者_开发问答hing like this
private void setEventListeners(){
mSpecialViewClass.getSubmitButton().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
handleSubmitClick();
}
});
}
private void handleSubmitClicks(){
if (counter<0){
writeCounterToDb();
} else {
//do some stuff
closeDatabase();
}
}
now this works nicely, but if I tap the button fast enough, I get a closed DB error
java.lang.IllegalStateException: database not open
How can I prevent the key listener from doing anything, before the previous key event has been handeled?
Edit: some user suggested closing my database on Activity.onDestroy() which is quite nice, and he deleted the answer. That is a nice workaround for my problem, but still not the solution I am looking for.
I also tried disabling the button and enabling the button on various positions, and the problem remains. It seems I can always achieve that the function gets called one too many times, if I tap the button too fast.
A good UI trick, that you could possibly use here, is to disable the button once the user clicks. Just do something like this:
@Override
public void onClick(View arg0) {
arg0.setEnabled(false);
handleSubmitClick();
}
You can of course enable the button at the end of your onClick function if you need to.
While the button is disabled the user won't be able to click on it, so you will never get two onClick events. What is more, the style of the button changes, so the user will know that clicking won't do anything.
This technique is used all over the place (Gmail's send button for instance) and I consider it good UI design.
Now if you want to permit your user to press a button multiple times, really really fast and never loose or skip a single press, you'll need to implement some sort of a queuing mechanism. But I can only imagine this being necessary in games where there is a matter of life and death :)
精彩评论