首页 > 解决方案 > Android Kotlin listview 适配器过滤器仅显示第一项

问题描述

我制作了一个自定义 ArrayAdapter 来填充我的列表,并添加了 edittext 来过滤列表视图,但列表视图只过滤第一项。

XML:

<EditText
    android:id="@+id/invoiceSearchFilter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Search invoice"
    android:padding="15sp"
    android:background="@drawable/edit_text_border"/>

<ListView
    android:id="@+id/listViewInvoiceSearchList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="60dp"
    android:layout_marginBottom="50dp"/>

科特林:

var listView = findViewById<ListView>(R.id.listViewInvoiceSearchList)
var adapter = InvoiceSearchListAdapter(this,idList, titleList, descList)

var thefilter = findViewById<EditText>(R.id.invoiceSearchFilter)
listView.adapter = adapter
thefilter.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
    
                }
    
                override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                    (listView.adapter as InvoiceSearchListAdapter).filter.filter(charSequence)
                }
    
                override fun afterTextChanged(editable: Editable) {
    
                }
            })

ListView 正确显示所有条目,但为什么我输入文本来过滤列表,它只过滤第一项。

标签: androidkotlinandroid-listviewandroid-arrayadapterandroid-adapter

解决方案


使用 foreach 过滤查询如下希望它也有助于toLowerCase(Locale.getDefault())避免区分大小写:

charSequence.forEach { q ->
           (listView.adapter as InvoiceSearchListAdapter).filter.filter(q)
        }

推荐阅读