我有姓名列表(名字 + 姓氏),并希望在该 listView 中按名字和姓氏进行搜索。我正在使用此代码仅按名称搜索
谁能给我提示需要对代码进行哪些更改以便我也可以按名字和姓氏进行搜索?
我有姓名列表(名字 + 姓氏),并希望在该 listView 中按名字和姓氏进行搜索。我正在使用此代码仅按名称搜索
谁能给我提示需要对代码进行哪些更改以便我也可以按名字和姓氏进行搜索?
ArrayAdapter 已经具备过滤功能,ListView 可以接受搜索文本,所以不需要重新发明轮子。
例子:
每当数据有多个对象时,让一个类保存数据:
Public class FullName {
public final String firstName;
public final String lastName;
public Fullname(String fn, String ln){
this.firstName = fn;
this.lastName = ln;
}
@Override
public String toString(){
// this is what ArrayAdapter uses for display and search
return firstName + " " + lastName;
}
}
内部活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView nameList = new ListView(this);
setContentView(nameList);
ArrayAdapter<FullName> nameAdapter = new ArrayAdapter<FullName>(this,android.R.layout.simple_list_item_1);
nameAdapter.add( new FullName("John","Doe") );
nameAdapter.add( new FullName("Bob","Carson") );
nameAdapter.add( new FullName("Kyle","Connor") );
nameList.setAdapter(nameAdapter);
//bring up the keyboard, start typing on a ListView and it will filter out matching results
nameList.setTextFilterEnabled(true);
}
如果您真的想使用 EditText 进行搜索:
nameAdapter.getFilter.filter(myEditText.getText());
清除过滤器:
nameAdapter.getFilter.filter(null);
只需遵循以下代码:
String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
"iPhone 4S", "Samsung Galaxy Note 800",
"Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
MainActivity.java
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});