2012-12-03 87 views
0

我有姓名列表(名字+姓氏),并希望通过该名单中的名字和姓氏进行搜索。我使用此代码由frstname只搜索想通过名字和姓氏在ListView中搜索名字?

Android Search in ListView Example

谁能给我暗示什么需要做的代码更改,这样我可以通过名字搜索,也姓?

+0

请在这里提供源代码 – Milind

+0

如何显示'姓'?它是'listview_array'还是一个单独的数组? –

+0

几周前我回答了这样的问题,这有帮助吗? [ArrayAdapter - 使用多个搜索词进行筛选](http://stackoverflow.com/q/13371160/1267661)至少,它会告诉您如何以及为什么需要创建自定义ArrayAdapter来执行非标准筛选。 – Sam

回答

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 
    } 
}); 
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);