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 ^^
2
Answers
You can use collection like this
Map<String, Int>
, whereString
is letter andInt
is position, then pass position value by letter toonLetterClick(position: Int)
and callscrollToPositionWithOffset(position,0)
.IMHO it’s better to use a prepared dictionary in your situation.
One way to do it is to maintain a
Map<String,Int>
orMap<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 followingNow pass this
map
to youradapter
and when any item is clicked, you can get the position of item frommap
as