You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android-Kotlin:Assets中JSON数据排序及搜索过滤问题求助

Kotlin RecyclerView数据排序与SearchView过滤解决方案

一、解决排序问题

你之前的注释代码出错,是因为station是StationsModelClass对象而非集合,要对它内部的stations列表排序。另外name是可空字符串,排序时必须处理空值避免空指针。

修正后的排序代码

try {
    val jsonString = readJsonFile(this, "stations.json")
    val stationModel = Gson().fromJson(jsonString, StationsModelClass::class.java)
    
    // 对stations列表按name排序,空name项排到末尾
    val sortedStations = stationModel.stations.sortedBy { 
        it.name ?: "" // 将空name替换为空字符串,保证排序逻辑正常执行
    }
    
    // 如果想直接修改原ArrayList(不生成新列表),可以用sortBy
    // stationModel.stations.sortBy { it.name ?: "" }
    
    binding.stationList.adapter = StationItemAdapter(ArrayList(sortedStations))
} catch (e: JSONException) {
    e.printStackTrace()
}

二、实现SearchView过滤功能

步骤1:修改Adapter支持数据更新

让Adapter维护数据列表,并提供更新方法:

class StationItemAdapter(private var stationList: List<Station>) : RecyclerView.Adapter<StationItemAdapter.ViewHolder>() {

    // ... 保留原有ViewHolder及数据绑定逻辑
    
    // 更新数据的方法
    fun updateData(newList: List<Station>) {
        stationList = newList
        notifyDataSetChanged()
    }
}

步骤2:布局中添加SearchView

在Activity布局里加入SearchView(示例放在Toolbar中):

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize">
    
    <androidx.appcompat.widget.SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:queryHint="搜索车站名称或别名"/>
</androidx.appcompat.widget.Toolbar>

步骤3:在MainActivity中设置SearchView监听

先保存原始数据列表,再根据输入关键词过滤:

private lateinit var originalStations: List<Station>
private lateinit var stationAdapter: StationItemAdapter

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    
    try {
        val jsonString = readJsonFile(this, "stations.json")
        val stationModel = Gson().fromJson(jsonString, StationsModelClass::class.java)
        originalStations = stationModel.stations.sortedBy { it.name ?: "" }
        
        stationAdapter = StationItemAdapter(originalStations)
        binding.stationList.adapter = stationAdapter
        
        // 设置SearchView监听
        setupSearchView()
    } catch (e: JSONException) {
        e.printStackTrace()
    }
}

private fun setupSearchView() {
    binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            filterStations(query)
            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean {
            filterStations(newText)
            return true
        }
    })
}

private fun filterStations(query: String?) {
    val filteredList = if (query.isNullOrBlank()) {
        // 输入为空时显示全部数据
        originalStations
    } else {
        val lowerCaseQuery = query.lowercase()
        originalStations.filter { station ->
            // 匹配name或synonym,忽略大小写
            station.name?.lowercase()?.contains(lowerCaseQuery) == true ||
            station.synonym?.lowercase()?.contains(lowerCaseQuery) == true
        }
    }
    stationAdapter.updateData(filteredList)
}

内容的提问来源于stack exchange,提问作者Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 08:01:30