Last active
March 18, 2019 12:45
-
-
Save 0neel/7d1ed5d26f2148b4168b6616337159ed to your computer and use it in GitHub Desktop.
KeyEvents handling from fragments - https://stackoverflow.com/a/43778858/2489474
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class KeyEventHandlingFragment extends Fragment | |
implements KeyEventPassingActivity.KeyEventListener { | |
@SuppressWarnings("deprecation") | |
@Override | |
public void onAttach(Activity activity) { | |
super.onAttach(activity); | |
if (activity instanceof KeyEventPassingActivity) { | |
((KeyEventPassingActivity) activity).addKeyEventHandler(this); | |
} | |
} | |
@Override | |
public void onDetach() { | |
Activity activity = getActivity(); | |
if (activity instanceof KeyEventPassingActivity) { | |
((KeyEventPassingActivity) activity).removeKeyEventHandler(this); | |
} | |
super.onDetach(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class KeyEventPassingActivity extends Activity { | |
public interface KeyEventListener extends View.OnKeyListener { | |
boolean isVisible(); | |
View getView(); | |
} | |
private final List<KeyEventListener> keyEventHandlerList = new ArrayList<>(); | |
@Override | |
public boolean dispatchKeyEvent(KeyEvent event) { | |
for (KeyEventListener handler : keyEventHandlerList) { | |
if (handleKeyEvent(handler, event)) { | |
return true; | |
} | |
} | |
return super.dispatchKeyEvent(event); | |
} | |
void addKeyEventHandler(@NonNull KeyEventListener handler) { | |
keyEventHandlerList.add(handler); | |
} | |
void removeKeyEventHandler(@NonNull KeyEventListener handler) { | |
keyEventHandlerList.remove(handler); | |
} | |
/** | |
* @return <tt>true</tt> if the event was handled, <tt>false</tt> otherwise | |
*/ | |
private boolean handleKeyEvent(@Nullable KeyEventListener listener, KeyEvent event) { | |
return listener != null | |
&& listener.isVisible() | |
&& listener.onKey(listener.getView(), event.getKeyCode(), event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment