【发布时间】:2021-04-23 13:05:08
【问题描述】:
我正在使用 API 制作应用程序并完美地获取所有数据。我在回收站视图上也有搜索栏。现在我想保存用户在应用程序上搜索的搜索历史。我已遵循 stackoverflow 的解决方案,但无法保存历史记录。
Search history in Android quick search
我想知道我必须在哪里制作 searchable.xml ?另外我正在使用edittext 在我的代码中执行搜索,所以我删除了edittext 并替换为searchable?
我在使用和设置content provider 时有点困惑。
我的xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:visibility="gone"/>
<TextView
android:id="@+id/txt_error_popular"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="@string/connection_problem"
android:visibility="gone"/>
<EditText
android:id="@+id/search_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionSearch"
android:inputType="text"
android:layout_marginEnd="10dp"
android:layout_marginStart="10dp"
android:hint="@string/search_for_something"
android:layout_marginBottom="4dp"
android:importantForAutofill="no" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_photos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
我正在执行搜索的main activity:
search(DEFAULT_SEARCH)
search_box?.setOnEditorActionListener(object : TextView.OnEditorActionListener{
override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
if (actionId == EditorInfo.IME_ACTION_SEARCH){
val searchTerm = search_box.text.trim()
if (searchTerm.isNotEmpty()){
rv_photos?.scrollToPosition(0)
photoAdapter.submitList(null)
search(searchTerm.toString())
currentFocus?.let {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(it.windowToken, HIDE_NOT_ALWAYS)
}
}
return true
}
return false
}
})
}
private fun search(searchTerm: String){
viewModel.performSearch(searchTerm)
}
现在我只想保存最近的搜索?
【问题讨论】:
-
您好,只需使用 roomDb 来存储您的搜索历史记录,每当用户点击搜索框时,即可获取搜索列表
-
@NitinPrakash:这里我不想使用任何数据库来存储历史记录。我只想将用户搜索的字符串存储在应用程序的搜索框中。例如,当我们点击 google 搜索引擎时,我们应该会看到我们之前的搜索 - 类似的东西。
-
那么如果不使用本地DB,如何获取之前的搜索字符串呢?
-
@NitinPrakash:谢谢你给我指导。我必须使用数据库。给你评论后,我搜索了很多,花时间,我用localDB解决了这个问题。
-
请接受我的回答
标签: android android-studio kotlin