开发者

How to filter text in a ListView properly?

开发者 https://www.devze.com 2023-01-18 14:27 出处:网络
I\'ve tried to filter my ListView from my EditText box, but currently, it\'s not working. I have a ListView that get data properly and they are added to my own ListView using a ArrayAdapter class and

I've tried to filter my ListView from my EditText box, but currently, it's not working.

I have a ListView that get data properly and they are added to my own ListView using a ArrayAdapter class and my own ArrayList class. When I for example, typing in "table" I want it to sort from the loaded titles in my ListView and than it should show me the items that are left and matching table.

My current code:

private ArrayList<Order> orders; /*开发者_JAVA技巧 ArrayList class with my own Order class to 
define title, info etc. */
private OrderAdapter adapter; //Own class that extends ArrayAdapter

orders = new ArrayList<Order>();
adapter = new OrderAdapter(this, R.layout.listrow, orders); /* listrow defining a
single item in my ListView */
setListAdapter(adapter); //Set our adapter to a ListView

search.addTextChangedListener(filterTextWatcher); //search is my EditText

private TextWatcher filterTextWatcher = new TextWatcher() {

    public void afterTextChanged(Editable s) {

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        adapter.getFilter().filter(s); //Filter from my adapter
        adapter.notifyDataSetChanged(); //Update my view
    }

};

Okay, so how can I achieve this? When I entering some value into the EditText box everything disappear, even if there is a match.

Thanks in advance and tell me if you need more code snippets or if this question i unclear!


The built-in filter implemented by ArrayAdapter converts the contained object to string by calling toString() method. It is this string that will be used to perform the matching. If you are only trying to match one string field in your Order object, you can override the toString() method for your Order class to return that field. If you want to perform more flexible matching, such as matching multiple fields, check out this post which shows how to create a custom filter:

Custom filtering in Android using ArrayAdapter

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号