下面的代码用于列表视图的搜索过滤器。每次更改tbSearch
editText中的文本时,都必须更改列表视图中的项目。执行在if语句(txt.length()==0)
内,但它不会添加我的数组。
public void onTextChanged(CharSequence s, int start, int before, int count) {
String txt = tbSearch.getText().toString().toLowerCase();
aaItems.clear();
if (txt.length() == 0)
{
aaItems.addAll(arrMonth);
}
else {
for (String item : arrMonth) {
if (item.toLowerCase().contains(txt)) {
aaItems.add(item);
}
}
}
}
答案 0 :(得分:2)
您传递给ArrayAdapter的List用作适配器的 支持ArrayList。
当您调用clear()时,您实际上正在清除您提供的支持数组。
您需要确保您为适配器提供的列表与您的arrMonth列表不同,如下所示:
>>>Ok
>>>This is a result
>>>1
>>>12345
答案 1 :(得分:0)
好的,我在@Michael Krause的帮助下解决了这个问题。多谢兄弟!我复制了另一个是temp的arraylist,并在textchangedlistener中使用。
public class ItemList extends Activity {
ListView lvItems;
EditText tbSearch;
//String[] arrMonth = {"January","February","March","April","May","June","July","August","September","October","November","December"};
ArrayList<String> arrMonth = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
ArrayAdapter<String> aaItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
lvItems = (ListView) findViewById(R.id.lvItems);
tbSearch = (EditText) findViewById(R.id.tbSearch);
PopulateArrayList();
temp.addAll(arrMonth);
aaItems = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrMonth);
lvItems.setAdapter(aaItems);
tbSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String txt = tbSearch.getText().toString().toLowerCase();
aaItems.clear();
if (s.length() == 0) {
aaItems.addAll(temp);
} else {
for (String item : temp) {
if (item.toLowerCase().contains(txt)) {
aaItems.add(item);
}
}
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public void btnAdd_Click(View v)
{
aaItems.add("Patrick");
}
public void PopulateArrayList()
{
arrMonth.add("January");
arrMonth.add("February");
arrMonth.add("March");
arrMonth.add("April");
arrMonth.add("May");
arrMonth.add("June");
arrMonth.add("July");
arrMonth.add("August");
arrMonth.add("September");
arrMonth.add("October");
arrMonth.add("November");
arrMonth.add("December");
}
}