Using an EditText to filter a SimpleCursorAdapter-backed ListView

前端 未结 2 965
南旧
南旧 2020-12-17 01:53

I have a ListView with a custom item layout backed by a SimpleCursorAdapter. I\'d like the user to be able to type text into an EditText box and have the ListView automatica

2条回答
  •  生来不讨喜
    2020-12-17 02:21

    well it's much more like arrayAdapter here is sample code

    public class ListViewFilter extends Activity {
    private ItemDatabaseHelper itemData;
    private SimpleCursorAdapter sc;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        itemData=new ItemDatabaseHelper(this);
        Cursor c=itemData.getAllValues(); 
    
        sc=new 
            SimpleCursorAdapter(this, R.layout.list_items, c, new String[]{itemData.VALUE}, new int[]{R.id.txtItem});
        ListView lv=(ListView)findViewById(R.id.lstItems);
        lv.setAdapter(sc);
        sc.setFilterQueryProvider(new FilterQueryProvider() {
    
            @Override
            public Cursor runQuery(CharSequence constraint) {
                String partialValue = constraint.toString();
                return itemData.getAllSuggestedValues(partialValue);
    
            }
        });
        EditText etext=(EditText)findViewById(R.id.etxtItemName);
        etext.addTextChangedListener(new TextWatcher() {
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
    
    
            }
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
    
    
            }
    
            @Override
            public void afterTextChanged(Editable s) {
                sc.getFilter().filter(s.toString());
    
            }
        });
    }
    

    }

    and two xml files are listed below

    main.xml is

    
    
    
    
    
    

    and list_item.xml is

      
    
    
    

    Hope this will help you

提交回复
热议问题