Skip to content

Commit

Permalink
Merge pull request #2 from Kyash/fix_crash
Browse files Browse the repository at this point in the history
Add rootView null check
  • Loading branch information
konifar authored May 20, 2018
2 parents 765808c + 5412643 commit 6b14d5e
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions library/src/main/java/co/kyash/rkd/KeyboardDetector.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class KeyboardDetector constructor(
return Observable.just(KeyboardStatus.CLOSED)
}

val rootView = (activity.findViewById<View>(android.R.id.content) as ViewGroup)
val rootView = (activity.findViewById<View>(android.R.id.content) as ViewGroup?)

val windowHeight = DisplayMetrics().let {
activity.windowManager.defaultDisplay.getMetrics(it)
Expand All @@ -33,6 +33,12 @@ class KeyboardDetector constructor(

return Observable.create<KeyboardStatus> { emitter ->
val listener = ViewTreeObserver.OnGlobalLayoutListener {
if (rootView == null) {
Log.w(TAG, "Root view is null")
emitter.onNext(KeyboardStatus.CLOSED)
return@OnGlobalLayoutListener
}

val rect = Rect().apply { rootView.getWindowVisibleDisplayFrame(this) }
val keyboardHeight = windowHeight - rect.height()

Expand All @@ -43,12 +49,13 @@ class KeyboardDetector constructor(
}
}

rootView.viewTreeObserver.addOnGlobalLayoutListener(listener)
rootView?.let {
it.viewTreeObserver.addOnGlobalLayoutListener(listener)

emitter.setCancellable {
rootView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
emitter.setCancellable {
it.viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
}

}.distinctUntilChanged()
}

Expand Down

0 comments on commit 6b14d5e

Please sign in to comment.