以下是一个使用Kotlin和RecyclerView实现搜索功能的示例代码:
data class Item(val id: Int, val name: String)
class ItemAdapter(private val items: List- ) : RecyclerView.Adapter
() {
private var filteredItems: List- = items
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_row, parent, false)
return ItemViewHolder(view)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = filteredItems[position]
holder.bind(item)
}
override fun getItemCount(): Int {
return filteredItems.size
}
fun filter(query: String) {
filteredItems = if (query.isEmpty()) {
items
} else {
items.filter { it.name.contains(query, true) }
}
notifyDataSetChanged()
}
inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(item: Item) {
itemView.textView.text = item.name
}
}
}
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var editText: EditText
private lateinit var itemAdapter: ItemAdapter
private val items = listOf(
Item(1, "Apple"),
Item(2, "Banana"),
Item(3, "Cherry"),
Item(4, "Grape"),
Item(5, "Lemon"),
Item(6, "Orange")
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recyclerView)
editText = findViewById(R.id.editText)
itemAdapter = ItemAdapter(items)
recyclerView.adapter = itemAdapter
recyclerView.layoutManager = LinearLayoutManager(this)
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
itemAdapter.filter(s.toString())
}
override fun afterTextChanged(s: Editable?) {}
})
}
}
请确保在布局文件中包含一个名为"recyclerView"的RecyclerView和一个名为"editText"的EditText。
这段代码将根据用户在EditText中输入的文本来过滤RecyclerView中的数据项,并通过调用filter()
方法在适配器中实现搜索功能。搜索结果将实时显示在RecyclerView中。