Search code examples
androidonkeydown

Helper's function to override `onKeyDown` whenever activity call the function?


I have many Activity which need to override onKeyDown event as below:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Do something here
        return false;
    }
    return super.onKeyDown(keyCode, event);
}

The problem here is that: I have many activities that should call the block of code above (no different in any activity). So I want to write an helper's function like:

 public static void overrideOnKeyDownFunction(...);

And, in any activity that need to override onKeyDown event (same with first code block), I can only call: Helper.overrideOnKeyDownFunction(...);!

Can I do some thing like this? And how to do it? Thanks in advance!


Solution

  • I think the best way of sharing that behavior between different activities is making all of them inherit from the same superclass that overrides the onKeyDown method.

    So, if you create an Activity with onKeyDown overriden (let's say OverridenBackKeyActivity) any Activity inheriting from OverridenBackKeyActivity will automatically inherit that behavior.