I have an Activity that contains four Buttons that all trigger the same onClick() method when clicked. I want to prevent concurrent calling/access of that method.
- When button1 is clicked, the onClick() method causes a scrolling horizontal Scrollview to scroll a few pixels and display another view.
- This newly displayed View has a back button to scroll back to the previous position. [Things are working as expected up to this point].
Problem:
If in the Activity two buttons are pressed simultaneously (or only a few milliseconds apart), then my custom scroll method calls again before completing first button click execution.
Tried Case:
- Using the synchronized keyword with the method, which is called from the button's onClick with UI thread. [Not working]
- Tried setting "static boolean flag," hasClicked to true during onClick() execution, and checking it immediately inside onClick(), returning if true. [Not working]
Related Code:
private OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
int viewId = view.getId();
//Proshop top icon
if(viewId == R.id.proshop_icon){
if(hasClicked){
return;
}
hasClicked = true;
mProShopIconTop.startAnimation(proShopButtonAnimation());
if(mHScrollView.getCurrentChildIndex() == 0){
addAndMoveToSecondPage(mProshopPageView, true);
} else {
addAndMoveToSecondPage(mProshopPageView, false);
}
hasClicked = false;
}
//Tune top icon
else if(viewId == mTuneIconTop.getId()){
if(hasClicked){
return;
}
hasClicked = true;
mTuneIconTop.startAnimation(tuneButtonAnimation());
if(mHScrollView.getCurrentChildIndex() == 0){
addAndMoveToSecondPage(mTunePageView, true);
} else {
addAndMoveToSecondPage(mTunePageView, false);
}
hasClicked = false;
}
//bottom and top aiConnect button
else if(viewId == mAiConnect.getId() || viewId == mAiConnectIconTop.getId()){
if(hasClicked){
return;
}
hasClicked = true;
mAiConnectIconTop.startAnimation(aiConnectButtonAnimation());
if(mHScrollView.getCurrentChildIndex() == 0){
addAndMoveToSecondPage(mAIConnectPageView, true);
} else {
addAndMoveToSecondPage(mAIConnectPageView, false);
}
hasClicked = false;
}
//DR page play game button
else if(viewId == mPlayGame.getId()){
if(hasClicked){
return;
}
hasClicked = true;
playGolfClick();
addAndMoveToSecondPage(mGameMenuPageView, true);
hasClicked = false;
}
}
}
This is code which I called from onCLick.
private void addAndMoveToSecondPage(View view, boolean withScroll){
mHScrollView.removePage(1);
mHScrollView.addPage(view, 1);
if(withScroll){
mHScrollView.moveToNextView();
}
view.setVisibility(View.VISIBLE);
}
mHScrollView is the instance of HorizontalScrollView which is customized by me, I incorporated the method below in my CustomHorizontalScrolView which is a sub-class of HorizontalScrolView.
public void moveToNextView(){
smoothScrollTo(getScrollX() + mScreenWidth, 0);
}
Any help will be appreciated.. Thanks in advance..!!