2017年7月9日 星期日

How to sort filter listview in android

When you use custom arrayadapter and listview in android, you may want to filter and sort the data, however, it is really often that sort and filter work well separately, however when you combine this two, the sort doesn't!
Below is my original code(not work):

public boolean onQueryTextChange(String newText) {
    xAdapter.getFilter().filter(newText, new Filter.FilterListener() {
        @Override
            public void onFilterComplete(int count){
                TextView one= (TextView) findViewById(R.id.xsort);
                one.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lsort(xListView);
                    }
                });
            }
        });

        return false;
}

After working for many hours, I found that the xListview is the same, it wasn't filtered, so I sort xListview before, then filter it, this time it works perfectly, the code is provided below!
// made newText final
public boolean onQueryTextChange(final String newText) {
    xAdapter.getFilter().filter(newText, new Filter.FilterListener() {
        @Override
            public void onFilterComplete(int count){
                TextView one= (TextView) findViewById(R.id.xsort);
                one.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lsort(xListView);
                        xAdapter.getFilter().filter(newText)// add this line

                    }
                });
            }
        });

        return false;
}

沒有留言:

張貼留言