Nam Vu
Nam Vu

Reputation: 5725

Avoid mutiple tap in button when run thread in Android

I have a button, when user tap the button, i run a Thread to do Something.

When user tap many time to my button, i have many thread run in a same time.

How can i avoid it, when user multiple tap, i have run only thread run. When the first thread complete, the second thread can run.

Thanks

Upvotes: 0

Views: 479

Answers (4)

codedip
codedip

Reputation: 191

Faced same issue in xamarin android. Fixed it in diffrent way. Same Idea also applicable for android Java developers.

public  class SingleClickListener
{
    public SingleClickListener(Action<object, EventArgs> setOnClick)
    {
        _setOnClick = setOnClick;
    }
    private bool hasClicked;

    private Action<object, EventArgs> _setOnClick;

    public void OnClick(object v, EventArgs e)
    {
        if (!hasClicked)
        {
            _setOnClick(v, e);
            hasClicked = true;
        }
        reset();
    }

    private void reset()
    {
        Android.OS.Handler mHandler = new Android.OS.Handler();
        mHandler.PostDelayed(new Action(() => { hasClicked = false; }), 500);
    }
}

Upvotes: 0

David Wasser
David Wasser

Reputation: 95618

You need to keep a boolean that indicates you've acted on the click and started the thread. Something like this:

boolean threadStarted = false;

public void onClick(View v) {
    if (!threadStarted) {
        // start thread here
        threadStarted = true;
    } else {
        // Ignore this spurious click
    }
}

Note: Don't forget to reset the boolean to false after the thread has completed

Upvotes: 2

Dhrupal
Dhrupal

Reputation: 1873

Use asynctask for process. you can see this. Using that if button is pressed once your ui will not able to touched untill the process is over.

Upvotes: 0

Tuna Karakasoglu
Tuna Karakasoglu

Reputation: 1267

Have you tried: Add myButton.setEnabled(false) when button pressed and then add myButton.setEnabled(true) to the end of the thread.

Upvotes: 2

Related Questions