Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event transferred to next started Activity

I'm affected by strange event handling in Android. My problem is that if user clicks at a Button many times really quick then event is queued and transferred further to next Activity.

Here is an example:

<Button
  android:id="@+id/btn_home_show"
  style="@style/main_buttons"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="@string/home_label_show" />

Activity onClick:

public void onClick(View view) {
    int viewId = view.getId();

    if (viewId == EXPECTED_VIEW_ID) {
        Intent intent = new Intent(this, CarouselActivity.class);
        startActivity(intent);
    }
}

In my Activity I have another item that is clickable with the same coordinates on the screen.

What happens is that if user click really fast on the Button then this click event is transfered to newly started Activity and another onClick handling occurs.

I tried 2.3.3 & 2.3.5 framework version & behavior is the same. Any ideas?

like image 690
pawel.urban Avatar asked Nov 05 '22 10:11

pawel.urban


1 Answers

A simple solution would be add a boolean value that determines whether or not a click is handled then create a thread that sleeps then sets the value to true

public void onClick(View view) {

    if (inputAllowed) {
        //do stuff
    }
}

boolean inputAllowed = true;
private class ButtonDelay extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Void doInBackground(Void... params) {

        try {
            inputAllowed = false;

            Thread.sleep(500);
            inputAllowed = true;
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(final Void unused) {

    }

}

And start the asynctask immediately in onCreate(). As for why this happens I guess the new activity has created the new button and since the user is rapidly clicking it registers these clicks.

like image 180
triggs Avatar answered Nov 13 '22 05:11

triggs