Last active
May 16, 2019 03:12
-
-
Save xujiaji/5f8ee87812bb064b3d8de10244eba125 to your computer and use it in GitHub Desktop.
android 键盘监听工具 kotlin
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
| import android.app.Activity | |
| import android.graphics.Rect | |
| import android.view.View | |
| import android.view.ViewGroup | |
| import android.view.ViewTreeObserver | |
| import android.app.Application | |
| import android.os.Bundle | |
| object KeyboardTool { | |
| private const val KEYBOARD_MIN_RATIO = 0.15 | |
| fun registerEvent(activity: Activity, listener: OnKeyboardListener) { | |
| val rootView = getActivityRoot(activity) | |
| val globalListener = object : ViewTreeObserver.OnGlobalLayoutListener { | |
| private val r = Rect() | |
| private var isOpened = false | |
| override fun onGlobalLayout() { | |
| rootView.getWindowVisibleDisplayFrame(r) | |
| val screenHeight = rootView.rootView.height | |
| val heightDiff = screenHeight - r.height() | |
| val isOpen = heightDiff > screenHeight * KEYBOARD_MIN_RATIO | |
| if (isOpen == isOpened) { | |
| return | |
| } | |
| isOpened = isOpen | |
| listener.onVisibleChange(isOpen) | |
| } | |
| } | |
| rootView.viewTreeObserver.addOnGlobalLayoutListener(globalListener) | |
| activity.application.registerActivityLifecycleCallbacks(object : ActivityDestroyCycleCallback(activity) { | |
| override fun onDestroyCycle() { | |
| rootView.viewTreeObserver.removeOnGlobalLayoutListener(globalListener) | |
| } | |
| }) | |
| } | |
| private fun getActivityRoot(activity: Activity): View = activity.findViewById<ViewGroup>(android.R.id.content).getChildAt(0) | |
| interface OnKeyboardListener { | |
| fun onVisibleChange(isOpen: Boolean) | |
| } | |
| } | |
| abstract class ActivityDestroyCycleCallback(private val mTargetActivity: Activity): Application.ActivityLifecycleCallbacks { | |
| override fun onActivityPaused(activity: Activity?) {} | |
| override fun onActivityResumed(activity: Activity?) {} | |
| override fun onActivityStarted(activity: Activity?) {} | |
| override fun onActivityDestroyed(activity: Activity?) { | |
| if (activity == mTargetActivity) { | |
| mTargetActivity.application.unregisterActivityLifecycleCallbacks(this) | |
| onDestroyCycle() | |
| } | |
| } | |
| override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {} | |
| override fun onActivityStopped(activity: Activity?) {} | |
| override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {} | |
| protected abstract fun onDestroyCycle() | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使用案例: