android - 是否可以过滤数组列表中的结果,然后将该列表添加到数组适配器?
问题描述
// 我在 allShops
JsonArrayRequest jsonArrayRequest 中从 db 获取数据;jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener() { @Override public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
//allShops is an arraylist
allShops.add(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
//user enters text in edittext et_search
et_search.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence cs, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s) {
//here i am adding arraylist to adapter but want it to happen after filtering the arraylist first based on users input
adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,allShops);
(Search.this).adapter.getFilter().filter(s);
lv_search.setAdapter(adapter);
}
});
解决方案
我更新了代码的闲置部分:
@Override
public void onTextChanged(CharSequence cs, int start, int before, int count)
{
if (cs.length()== 0)
{
adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,new ArrayList<String>());
//(Search.this).adapter.getFilter().filter(cs);
lv_search.setAdapter(adapter);
}
else
{
List<String> filtered = new ArrayList<String>();
for(String x:allShops)
{
if (x.toLowerCase().contains(cs.toString().toLowerCase()))
{
filtered.add(x);
}
}
adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,filtered);
lv_search.setAdapter(adapter);
}
}
推荐阅读
- networking - 签名社交网络示例
- r - 如何从 R 中的散点图中获取样本信息(或门控)?
- java - 尝试使用 Liquidbase 运行触发器时出现错误
- vb.net - Outlook 项目 Unicode
- javascript - 反应本机获取数据
- css - 在浏览器的 100% 和 80% 缩放级别上,将弹出窗口保持在同一位置
- types - INCLUDE 中的声明在主程序中不被识别
- python - Python -V 在 Windows 10 上不起作用或返回任何错误
- angular - 忽略未捕获的错误错误:服务器提前终止,状态为 3221225477
- c# - 在 Xamarin 的 xmlns 中找不到类型 Ellipse