我有名字列表(名字+姓氏),想要按照listView中的名字和姓氏进行搜索。我使用此代码仅按frstname搜索
Android Search in ListView Example
任何人都可以提示我需要对代码进行哪些更改以便我可以使用Firstname和lastname进行搜索吗?
答案 0 :(得分:0)
只需按照以下代码:
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
}
});
答案 1 :(得分:0)
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);