Issue
I am building a small dictioanry app, screenshot below:
When I click on a letter from mRecyclerView1, I want to scroll mRecyclerView2 to the the first word which starts with this particular letter.
Inside the mRecyclerView1 adapter I've made an interface which gets the value of the clicked letter.
Then inside the fragment I found a workaround with scrollToPositionWithOffset inside the onLetterClick method which looks like this:
override fun onLetterClick(letter: String) {
when (letter) {
"А" -> {
(mRecyclerView2!!.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
0,
0
)
}
"Б" -> {
(mRecyclerView2!!.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
140,
0
)
}
}
The problem is that I have to add all letters from the alphabet together with the positions of the first words that start with them. And if I decide to add more words later on, these positions will be shifted and will change.
Is there a smarter way to achieve this scroll effect? If not, is it possible to make a for/while loop instead of using when with all alphabet letters?
Any help will be appreciated! Thank you ^^
Solution
One way to do it is to maintain a Map<String,Int> or Map<Char, Int> (Your choice) which contains index of first word starting with given character. for example ("A" -> 0 , "B" -> 5 ) etc.
In your case you can prepare the map when you load the data in RecyclerView like following
val list = // This is list of words
val map = mutableMapOf<String, Int>()
list.forEachIndexed { index, s ->
map.putIfAbsent(s[0].toString(), index) // Handle lowercase/uppercase if required
}
Now pass this map to your adapter and when any item is clicked, you can get the position of item from map as
map[word[0].toString()]
Answered By - mightyWOZ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.