Add Beforeclick and Afterclick events to a button

Asked

Viewed 43 times

1

I created a new class that inherits the Button component. I’ll call this class "Novobutton".

This Novobutton will work as the traditional Button, but the onClick event needs to run 2 more new listeners:

1. before the onClick code;
2. after the onClick code.

We can say that this Novobutton will have an "Onbeforeclicklistener", the traditional Onclicklistener and an "Onafterclicklistener".

With this, when the person clicks, 3 events can be triggered.

I created two interfaces (Onbeforeclicklistener and Onafterclicklistener) and this Novobutton class implements them.

My question is this::

How do I call beforeClick and afterClick respectively before and after the onClick event that Novobutton inherited from Button?

1 answer

2


When a View is "clicked" the implementation of the View class calls the method onClick() implementation of the Onclicklistener interface, indicated by the method setOnClickListener().

As it is not possible to know beforehand that the button will be clicked, the method beforeClick() has to be called in the method onClick().

How to implement the onClick() is specified by the user of the class, you need to find a way to have that code executed after executing beforeClick() and before executing afterClick().
That is, when clicking the button, the code to be executed has to be implemented by you, in order to respect that sequence, and not the one indicated by the user, through the method setOnClickListener().

So you have to do the override of the method setOnClickListener() so that your Onclicklistener implementation is used, the one that runs in sequence beforeClick(), onClick() and afterClick().

private OnClickListener mUserOnClickListener;
private OnClickListener mMyOnClickListener;
private OnBeforeClickListener mOnBeforeClickListener;
private OnAfterClickListener mOnAfterClickListener;

@override
public void setOnClickListener(OnClickListener l) {
    mUserOnClickListener = l;
    super.setOnClickListener(mMyOnClickListener);
}

The method onClick() of mMyOnClickListener will be anything like:

@override
public void onClick(View v){
    mOnBeforeClickListener.beforeClick(v);
    mUserOnClickListener.onClick(v);
    mOnAfterClickListener.afterClick(v);
}

Do not forget to check if the listeners are not null.

  • Thanks. It worked out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.