Skip to content

Commit

Permalink
Disable onBackPressed when components are destroyed
Browse files Browse the repository at this point in the history
  • Loading branch information
basshelal committed Jul 29, 2019
1 parent 1ca4517 commit 57323a6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ class PhotoPickerFragment
?.commit()
}

override fun onDestroy() {
super.onDestroy()

onBackPressed.isEnabled = false
}

companion object {
const val TAG = "UnsplashPhotoPickerFragment"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,12 @@ public class PhotoShowFragment : Fragment() {
?.commit()
}

override fun onDestroy() {
super.onDestroy()

onBackPressed.isEnabled = false
}

companion object {
const val TAG = "UnsplashPhotoPickerPhotoShowFragment"
private const val PHOTO = "PHOTO"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,16 @@ public class UnsplashPhotoPicker
}
}

// When the user has searched something, a back press will clear the selection
val onBackPressed = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
if (this@UnsplashPhotoPicker.search_editText?.text?.isNotBlank() == true) {
clearSelectedPhotos()
this@UnsplashPhotoPicker.search_editText?.text = SpannableStringBuilder("")
}
}
}

//endregion Privates

//region Public API
Expand Down Expand Up @@ -348,15 +358,6 @@ public class UnsplashPhotoPicker
searchCardView?.isVisible = hasSearch
searchEditText?.hint = searchHint

// When the user has searched something, a back press will clear the selection
val onBackPressed = object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
if (this@UnsplashPhotoPicker.search_editText?.text?.isNotBlank() == true) {
clearSelectedPhotos()
this@UnsplashPhotoPicker.search_editText?.text = SpannableStringBuilder("")
}
}
}
activity.onBackPressedDispatcher.addCallback(onBackPressed)

adapter = UnsplashPhotoAdapter(
Expand Down Expand Up @@ -598,6 +599,14 @@ public class UnsplashPhotoPicker
}
}

override fun onDetachedFromWindow() {
super.onDetachedFromWindow()

// If the caller destroyed this View when the search bar was full
// we must disable the onBackPressed to avoid "empty" back presses
onBackPressed.isEnabled = false
}

//endregion Private functions
}

Expand Down

0 comments on commit 57323a6

Please sign in to comment.