我有一个活动,其中包含一个RecyclerView,我想使用我设置的SearchView对其进行过滤。
class ExerciseCatalogueActivity : AppCompatActivity(), ExerciseClickedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_exercise_catalogue_activity)
val toolbar = toolbar_catalogue
setSupportActionBar(toolbar)
val exercisesCatalogueList : MutableList<Exercise>
val exerciseCatalogueFullList: MutableList<Exercise>
val exerciseFileString: String = resources.openRawResource(R.raw.exercises1).bufferedReader().use { it.readText() }
exercisesCatalogueList = (Gson().fromJson(exerciseFileString, Array<Exercise>::class.java)).toMutableList()
exerciseCatalogueFullList = ArrayList<Exercise>(exercisesCatalogueList)
rv_catalogue.apply {
rv_catalogue.layoutManager = LinearLayoutManager(context, LinearLayout.VERTICAL, false)
adapter = ExerciseCatalogueRecyclerViewAdapter(exercisesCatalogueList,exerciseCatalogueFullList, this@ExerciseCatalogueActivity)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.toolbar_menu, menu)
val searchItem = menu!!.findItem(R.id.action_search_bar)
val searchView = searchItem.actionView as SearchView
searchView.imeOptions = EditorInfo.IME_ACTION_DONE
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(newText: String): Boolean {
adapter.filter.filter(newText)
return false
}
})
return true
}
}
但是adapter.filter.filter(newText)
返回为未解决,我无法过滤我的recyclerView。需要进行哪些更改?
答案 0 :(得分:1)
您尚未保存对适配器的引用。
您可以在名为rv_catalogue
的RecyclerView上使用.apply,以便在范围内工作。
在onCreateOptionsMenu
中,没有要引用的适配器。
在“活动”中保存对适配器的引用,或使用rv_catalogue.adapter
获取对适配器的引用。