feat: 新增搜索历史与AI智能体搜索功能
- 新增搜索历史记录功能,使用 SharedPreferences + JSON 进行本地存储。 - 搜索页在无搜索结果时展示历史记录,支持点击搜索、长按删除单个记录和清空全部历史。 - 新增 "AI" 搜索标签页,用于根据关键字搜索智能体(Agent)。 - 搜索页离开时自动重置搜索状态和文本,返回后显示历史记录。 - 优化了搜索逻辑,在输入文本为空时自动隐藏搜索结果并显示历史记录。
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
package com.aiosman.ravenow.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.reflect.TypeToken
|
||||
|
||||
/**
|
||||
* 搜索历史存储(SharedPreferences + JSON)
|
||||
* - 最多保留 maxSize 条
|
||||
* - 新记录放首位,去重(忽略前后空格)
|
||||
*/
|
||||
class SearchHistoryStore(context: Context) {
|
||||
private val prefs: SharedPreferences =
|
||||
context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
|
||||
private val gson = Gson()
|
||||
|
||||
fun getHistory(): List<String> {
|
||||
val json = prefs.getString(KEY_HISTORY, "[]") ?: "[]"
|
||||
return runCatching {
|
||||
val type = object : TypeToken<List<String>>() {}.type
|
||||
gson.fromJson<List<String>>(json, type) ?: emptyList()
|
||||
}.getOrDefault(emptyList())
|
||||
}
|
||||
|
||||
fun add(term: String) {
|
||||
val normalized = term.trim()
|
||||
if (normalized.isEmpty()) return
|
||||
val current = getHistory().toMutableList()
|
||||
current.removeAll { it.equals(normalized, ignoreCase = true) }
|
||||
current.add(0, normalized)
|
||||
while (current.size > MAX_SIZE) current.removeLast()
|
||||
save(current)
|
||||
}
|
||||
|
||||
fun remove(term: String) {
|
||||
val normalized = term.trim()
|
||||
val current = getHistory().toMutableList()
|
||||
current.removeAll { it.equals(normalized, ignoreCase = true) }
|
||||
save(current)
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
save(emptyList())
|
||||
}
|
||||
|
||||
private fun save(list: List<String>) {
|
||||
prefs.edit().putString(KEY_HISTORY, gson.toJson(list)).apply()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PREF_NAME = "search_history_pref"
|
||||
private const val KEY_HISTORY = "search_history_v1"
|
||||
private const val MAX_SIZE = 10
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user