skip to Main Content

I am building a small dictioanry app, screenshot below:

Screenshot

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


  1. You can use collection like this Map<String, Int>, where String is letter and Int is position, then pass position value by letter to onLetterClick(position: Int) and call scrollToPositionWithOffset(position,0).
    IMHO it’s better to use a prepared dictionary in your situation.

    Login or Signup to reply.
  2. 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()]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search