【问题标题】:On clearing the data in search view, it should erase the filtered list and populate the original list在清除搜索视图中的数据时,它应该删除过滤列表并填充原始列表
【发布时间】:2020-05-14 19:52:03
【问题描述】:

HomeFragment.kt

 override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return setupBindings(inflater, container, savedInstanceState)

}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String): Boolean {
            //filter the data in step 2
            return false
        }

        override fun onQueryTextChange(query: String): Boolean {
            orderHistoryViewModel.search(query)
            return false
        }
    })
}

我在 Fragment 中编写了 setOnQueryTextListener。当我运行该应用程序时,它只工作一次。但是,每次我从搜索栏中清除数据并在输入新数据时再次过滤时,如何删除过滤列表并填充原始列表。

我在 viewmodel 中编写了搜索功能。下面的代码从原始列表中过滤数据并填充过滤后的列表。

ViewModel.kt

fun search(query: String) {

    var filteredList =
        orderHistoryDetails?.orderList?.value?.filter { x -> x.order.contains(query) }

    orderHistoryDetails?.orderList?.value = filteredList

}

【问题讨论】:

  • 不要覆盖您的原始列表。检查query,如果是empty,则返回原始列表,否则返回过滤列表

标签: android kotlin searchview


【解决方案1】:

您还需要存储原始列表,并检查查询字符串是否为空。

 fun search(text: String) {
        val filterList: MutableList<OrderItem> = arrayListOf()
        if (text.trim().length == 0) {
            filterList.clear()
            filterList.addAll(listOriginal)
            notifyDataSetChanged()
        } else {
            listOriginal.filter {x->
              x.order.toUpperCase.contains(text)
            }.apply {
                filterList.clear()
                filterList.addAll(this)
            }
            notifyDataSetChanged()
        }
    }

【讨论】:

  • 我已经尝试过了,搜索只工作一次。当我清除数据并输入新数据时,过滤不会再次发生。
  • 可能是您的原始列表已被过滤列表覆盖,我已按照我使用和为我工作的方式更新了我的答案,并且我的答案中可能需要一些变量更正,请检查它是否有帮助.
  • 我已经修复了这个错误。现在工作正常。非常感谢
  • 太棒了。如果它对您有帮助,请考虑接受并投票,这样它也可以帮助其他人。
  • 当没有结果时,我必须显示“未找到详细信息”并且此卡片视图应该消失。我该怎么做?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
相关资源
最近更新 更多