【问题标题】:How to scroll recyclerview onItemClick in another recyclerview?如何在另一个 recyclerview 中滚动 recyclerview onItemClick?
【发布时间】:2021-09-30 14:04:30
【问题描述】:

我正在构建一个小型词典应用程序,截图如下:

Screenshot

当我点击来自mRecyclerView1 的字母时,我想将mRecyclerView2 滚动到以该特定字母开头的第一个单词。

mRecyclerView1 adapter 中,我创建了一个interface,它获取点击字母的值。 然后在片段中,我在onLetterClick 方法中找到了scrollToPositionWithOffset 的解决方法,如下所示:

override fun onLetterClick(letter: String) {
    when (letter) {
        "А" -> {
            (mRecyclerView2!!.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                0,
                0
            )
        }
        "Б" -> {
            (mRecyclerView2!!.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                140,
                0
            )
        }
    }

问题是我必须将字母表中的所有字母与以它们开头的第一个单词的位置一起添加。如果我以后决定添加更多的单词,这些位置将会移动并改变。

有没有更聪明的方法来实现这种滚动效果?如果没有,是否可以创建一个for/while 循环而不是使用带有所有字母的when

任何帮助将不胜感激!谢谢^^

【问题讨论】:

    标签: android-studio kotlin android-recyclerview


    【解决方案1】:

    您可以像Map<String, Int> 这样使用集合,其中String 是字母,Int 是位置,然后将位置值逐个字母传递给onLetterClick(position: Int) 并调用scrollToPositionWithOffset(position,0)。 恕我直言,最好在您的情况下使用准备好的字典。

    【讨论】:

      【解决方案2】:

      一种方法是维护一个Map<String,Int>Map<Char, Int>(您的选择),其中包含以给定字符开头的第一个单词的索引。例如("A" -> 0 , "B" -> 5 ) 等。

      在您的情况下,您可以在RecyclerView 中加载数据时准备地图,如下所示

      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
       }
      

      现在将此map 传递给您的adapter,当单击任何项​​目时,您可以从map 获取项目的位置

      map[word[0].toString()]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-20
        • 1970-01-01
        • 1970-01-01
        • 2021-08-29
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        相关资源
        最近更新 更多