Last active
August 30, 2019 08:32
-
-
Save gpetuhov/6ceca30ebcbc19fef2ad4e8f9f37d31e to your computer and use it in GitHub Desktop.
Android detect keyboard
This file contains hidden or 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
| // Android detect keyboard | |
| abstract class KeyboardDetectorFragment : Fragment() { | |
| private lateinit var layoutChangeListener: View.OnLayoutChangeListener | |
| init { | |
| initLayoutChangeListener() | |
| } | |
| override fun onResume() { | |
| super.onResume() | |
| addKeyboardDetector() | |
| } | |
| override fun onPause() { | |
| super.onPause() | |
| removeKeyboardDetector() | |
| } | |
| // === Protected methods === | |
| protected abstract fun onShowKeyboard() | |
| protected abstract fun onHideKeyboard() | |
| // === Private methods === | |
| // Show or hide help text and icon on keyboard show or hide. | |
| private fun initLayoutChangeListener() { | |
| layoutChangeListener = | |
| View.OnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> | |
| val oldHeight = oldBottom - oldTop | |
| val height = bottom - top | |
| // 0.15 ratio is perhaps enough to determine keypad height | |
| val ratio = 0.15 | |
| if (height < oldHeight && (oldHeight - height) > ratio * oldHeight) { | |
| // If new screen is smaller, than before, | |
| // then keyboard is shown | |
| onShowKeyboard() | |
| } else if (height > oldHeight && (height - oldHeight) > ratio * height) { | |
| // If new screen is bigger, than before, | |
| // then keyboard is hidden | |
| onHideKeyboard() | |
| } | |
| } | |
| } | |
| // This will be triggered only if windowSoftInputMode="adjustResize" is set for the activity. | |
| private fun addKeyboardDetector() = | |
| getActivityRootView()?.addOnLayoutChangeListener(layoutChangeListener) | |
| private fun removeKeyboardDetector() = | |
| getActivityRootView()?.removeOnLayoutChangeListener(layoutChangeListener) | |
| private fun getActivityRootView() = activity?.findViewById<View>(R.id.main_activity_root_view) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment