Search code examples
javaonclicklistenerandroid-button

Creating CustomButton Extends Button to pre set conditions which called before onclick


I have extended the Button class and I want to run methods like isInternetConnected and isUserLoggedIn when user click to this button and after perform onclick if all condition satisfied.

For Example if I created simple form where user name, email, phone no. and Submit Button placed. When user click on submit first it checks isInternetConnected and isUserLoggedIn if this satisfies then perform final operation saves user data to server or anywhere.

public class CustomButton extends Button {
private static final String TAG = "CustomButton";

public CustomButton(Context context) {
    super(context);
}

public CustomButton(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public CustomButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

If this is possible then I don't need to check every time

  `mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isInternetConnected) {
                //show dialog or snackbar
            } else if (!isUserLoggedIn) {
                //show dialog or snackbar
            }else {
                // save data
            }
        }
    });`

Solution

  • Now i understand what you are asking. Ideal solution for your problem would be AOP (aspect oriented programming). These should help you:

    https://medium.com/@jdvp/aspect-oriented-programming-in-android-159054d52757 https://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/

    This lib should help you:

    https://www.eclipse.org/aspectj/