Skip to content

Commit

Permalink
apply best practice to snackbar
Browse files Browse the repository at this point in the history
  • Loading branch information
RicardoTaipe committed May 18, 2024
1 parent 5443f99 commit 9e872ab
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class TasksFragment : Fragment(), MenuProvider {
}

private fun setupSnackbar() {
view?.setupSnackbar(viewLifecycleOwner, viewModel.snackbarText, Snackbar.LENGTH_SHORT)
view?.setupSnackbar(viewLifecycleOwner, viewModel.snackbarText, Snackbar.LENGTH_SHORT, binding.addTaskFab)
arguments?.let {
viewModel.showEditResultMessage(args.userMessage)
}
Expand Down
10 changes: 7 additions & 3 deletions app/src/main/java/com/example/todoapp/util/ViewExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import com.google.android.material.snackbar.Snackbar
/**
* Transforms static java function Snackbar.make() to an extension function on View.
*/
fun View.showSnackbar(snackbarText: String, timeLength: Int) {
fun View.showSnackbar(snackbarText: String, timeLength: Int, anchorView: View?) {
Snackbar.make(this, snackbarText, timeLength).run {
addCallback(object :Snackbar.Callback(){
override fun onShown(sb: Snackbar?) {
Expand All @@ -26,6 +26,9 @@ fun View.showSnackbar(snackbarText: String, timeLength: Int) {
}
})
animationMode = BaseTransientBottomBar.ANIMATION_MODE_SLIDE
if(anchorView != null){
this.anchorView = anchorView
}
show()
}
}
Expand All @@ -36,12 +39,13 @@ fun View.showSnackbar(snackbarText: String, timeLength: Int) {
fun View.setupSnackbar(
lifecycleOwner: LifecycleOwner,
snackbarEvent: LiveData<Event<Int>>,
timeLength: Int
timeLength: Int,
anchorView: View? = null
) {

snackbarEvent.observe(lifecycleOwner) { event ->
event.getContentIfNotHandled()?.let {
showSnackbar(context.getString(it), timeLength)
showSnackbar(context.getString(it), timeLength, anchorView)
}
}
}
Expand Down

0 comments on commit 9e872ab

Please sign in to comment.