Question

I'm trying to create an app that when pressing a button you get a different result each time. I'm using a global int named 'counter' that grows by +1 every time.

My problem is that if I press the button several times quickly it "jumps" to the end. How can I create a space between each press?

I thought using handler.postDelayed(Runnable, 500); but I'm not sure wether it's the best solution. And also - when and how to use it in the code?

Thanks.

public class MyMain extends Activity implements OnClickListener {

int clickCounter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_my_main);

    findViewById(R.id.button1).setOnClickListener(this);
    findViewById(R.id.button2).setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.button2:
        clickCounter = 0;
        break;
    case R.id.button1:
        clickCounter++;
        ActionByClick();
        break;
    }
}

private void ActionByClick() {
    // TODO Auto-generated method stub
    if (clickCounter == 1){

    } else if (clickCounter == 2){

    } else if (clickCounter == 3){

    } else if (clickCounter == 4){

    }
}

}
Was it helpful?

Solution

You can create a Timer that have a threshold that will check each time you press the button so you cant click on it for a certain time.

example:

     @Override
public void onClick(View v) {
    // Preventing multiple clicks, using threshold of 0.5 second
    if (SystemClock.elapsedRealtime() - mLastClickTime < 500) {
        return;
          }
    mLastClickTime = SystemClock.elapsedRealtime();

    ///YOUR BUTTON CLICK HERE
}

if (SystemClock.elapsedRealtime() - mLastClickTime < 500) checks if the last occurred click was .5 second already.

OTHER TIPS

You can use this code:

@Override
public void onClick(final View v) {

    // do stuff

    // Disable the button when it's clicked
    v.setEnabled(false);

    v.postDelayed(new Runnable(){
        @Override
        public void run() {

            // Enable it after 500ms
            v.setEnabled(true);

        }
    }, 500);   
}

That way, when the button is clicked it becomes disabled and after 500ms it comes back to enabled state.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top