如何使用 AutoCompleteTextView 并使用来自 Web API 的数据填充它?
我想在我的活动中使用 AutoCompleteTextView
并通过查询 Web API 在用户键入时填充数据。我该怎么做呢?
我是创建一个新类并覆盖 AutoCompleteTextView.performFiltering ,还是使用自定义列表适配器并提供覆盖 PerformFiltering 的自定义 android.widget.Filter ?
或者有更好的方法来实现我的最终目标吗?
我已经做了一些类似的事情,但它是针对快速搜索框的,并且涉及实现服务,但我相信这不是我想要在这里做的。
I want to use an AutoCompleteTextView
in my activity and populate the data as the user types by querying a web API. How do I go about doing this?
Do I create a new class and override AutoCompleteTextView.performFiltering
, or do I use a custom list adapter and provide a custom android.widget.Filter
that overrides performFiltering?
Or is there a better way to obtain my end goal?
I've done something somewhat similar, but it was for the Quick Search box and it involved implementing a service, but I believe that's not what I want to do here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我想出了一个解决方案,我不知道它是否是最好的解决方案,但它似乎工作得很好。我所做的是创建一个扩展 ArrayAdapter 的自定义适配器。在自定义适配器中,我重写了 getFilter 并创建了自己的 Filter 类来重写 PerformFiltering。这将启动一个新线程,因此不会中断 UI。下面是一个简单的例子。
MyActivity.java
AutoCompleteAdapter.java
I came up with a solution, I don't know if it is the best solution, but it appears to work very well. What I did was created a custom adapter that extends ArrayAdapter. In the custom adapter I overrode getFilter and created my own Filter class that overrides performFiltering. This starts a new thread so it doesn't interrupt the UI. Below is a barebones example.
MyActivity.java
AutoCompleteAdapter.java
扩展 AJ. 上面的答案,以下自定义适配器还包括服务器请求的处理和 json 解析:
并以同样的方式使用它:
Expanding on AJ.'s answer above, the following custom adapter includes the handling of the server requests and json parsing as well:
and use it the same way:
Chu:要自定义视图的外观并更好地控制展开对象,请执行以下操作......
Chu: To customize how the view looks and get more control over unwrapping the object, do the following...
自动完成用户适配器
AutoCompleteUserAdapter
下面是 Adapter 类的 Kotlin 版本,它通过 Room:
DAO 方法定义从本地数据库加载数据:
Here is a Kotlin version of the Adapter Class that loads data from a local database via Room:
DAO method definition: