我正在尝试通过允许用户搜索来用卡片搜索回收者视图。用户搜索时,卡片应“重新组织”以根据用户输入的字符显示。我曾尝试这样做,但这样做时遇到了问题。任何帮助表示赞赏。
MainActivity.kt
class MainActivity : AppCompatActivity(), BottomSheetRecyclerViewAdapter.ListTappedListener {
private var customAdapter: CustomAdapter? = null
private var arrayListModel = ArrayList<Model>()
private lateinit var bottomSheetBehavior: CustomBottomSheetBehavior<ConstraintLayout>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val modelList = readFromAsset()
val adapterList = CustomAdapter(modelList, this)
customAdapter = CustomAdapter(arrayListModel, this@MainActivity)
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout) as CustomBottomSheetBehavior
recyclerView.adapter = adapterList
recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
et_search.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (!s.isNullOrEmpty()) {
val searchList = ArrayList<Model>()
for (i in arrayListModel.indices) {
if (arrayListModel[i].name.toLowerCase().contains(s)) {
searchList.add(arrayListModel[i])
}
}
try {
customAdapter?.notifyDataSetChanged()
recyclerView.adapter = CustomAdapter(searchList, this@MainActivity)
} catch (e: Exception) {
e.printStackTrace()
}
} else {
customAdapter?.notifyDataSetChanged()
recyclerView.adapter = customAdapter
}
}
})
}
override fun onClickList(text: String) {
}
private fun readFromAsset(): List<Model> {
val modeList = mutableListOf<Model>()
val bufferReader = application.assets.open("android_version.json").bufferedReader()
val json_string = bufferReader.use {
it.readText()
}
val jsonArray = JSONArray(json_string);
for (i in 0..jsonArray.length() - 1) {
val jsonObject: JSONObject = jsonArray.getJSONObject(i)
val model = Model(jsonObject.getString("name"), jsonObject.getString("version"))
modeList.add(model)
}
return modeList
}
}
以下是您可以考虑/尝试的一种干净方法:使您的适配器实现可过滤的接口。提供您自己的Filter对象,在其中实现您的过滤逻辑(asynch)。您也可以使用SearchView代替在EditText上使用onTextChange。
所以:onTextChange(newText)=>调用adapter.getFilter()。filter(newText)=>过滤在后台发生(调用filter方法performFiltering)=>当过滤列表准备就绪(调用filter方法publishResults)时,按下将其添加到您的适配器中,然后notifyDataSetChanged。
希望这会有所帮助。这是有关如何实现此目的的干净示例:Example