我已经通过使用带有搜索字符串的 EditText 在我的应用程序中实现了搜索。
在此 EditText 下方,我有我想要执行搜索的 ListView。
<EditText
android:id="@+id/searchInput"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/input_patch"
android:gravity="center_vertical"
android:hint="@string/search_text"
android:lines="1"
android:textColor="@android:color/white"
android:textSize="16sp" >
</EditText>
<ListView
android:id="@+id/appsList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/searchInput"
android:cacheColorHint="#00000000" >
</ListView>
搜索EditText下方的列表会根据在EditText中输入的搜索文本而变化。
etSearch = (EditText) findViewById(R.id.searchInput);
etSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
searchList();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
函数 searchList() 进行实际搜索
private void searchList() {
String s = etSearch.getText().toString();
int textlength = s.length();
String sApp;
ArrayList<String> appsListSort = new ArrayList<String>();
int appSize = list.size();
for (int i = 0; i < appSize; i++) {
sApp = list.get(i);
if (textlength <= sApp.length()) {
if (s.equalsIgnoreCase((String) sApp.subSequence(0, textlength))) {
appsListSort.add(list.get(i));
}
}
}
list.clear();
for (int j = 0; j < appsListSort.size(); j++) {
list.add(appsListSort.get(j));
}
adapter.notifyDataSetChanged();
}
这里list 是显示在ListView 中的ArrayList,adapter 是ListView 适配器。
我希望这对您有所帮助。