Skip to content

Commit

Permalink
Restore previous scrolling position of Note list after coming back fr…
Browse files Browse the repository at this point in the history
…om search result
  • Loading branch information
tuancoltech committed Sep 26, 2024
1 parent 9a5fd37 commit 482fe08
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,19 @@ class NotesFragment: Fragment() {
binding.groupSearchResultEmpty.gone()
}
notesAdapter?.updateData(notes, fromSearch = true, keyword = text.toString())

//When search text is cleared, restore previous note item position in the list
if (text.toString().isEmpty() && binding.edtSearch.hasFocus()) {
binding.rvPinnedNotes.layoutManager?.scrollToPosition(lastNoteItemPosition)
}
}
})

binding.edtSearch.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
lastNoteItemPosition = getCurrentScrollPosition()
}
}
}

private fun onNotesLoaded(notes: List<Note>) {
Expand Down Expand Up @@ -251,8 +262,12 @@ class NotesFragment: Fragment() {

override fun onPause() {
super.onPause()
lastNoteItemPosition = getCurrentScrollPosition()
}

private fun getCurrentScrollPosition(): Int {
val layoutMgr = (binding.rvPinnedNotes.layoutManager as? LinearLayoutManager)
lastNoteItemPosition = layoutMgr?.findFirstCompletelyVisibleItemPosition() ?: 0
return layoutMgr?.findFirstCompletelyVisibleItemPosition() ?: 0
}

override fun onResume() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,13 @@ class NotesViewModel @Inject constructor(
//triggered within 0.5 second window.
delay(500)
notes.collectLatest {
val filteredNotes = it.filter { note ->
note.title.contains(keyword, true)
}
val filteredNotes = it
.filter { note ->
note.title.contains(keyword, true)
}

//Keep the search result ordered chronologically
.sortedByDescending { note -> note.resource?.modified }
withContext(Dispatchers.Main) {
onSuccess(filteredNotes)
}
Expand Down

0 comments on commit 482fe08

Please sign in to comment.