Вопрос

I want to implement an activity which have search functionality that searches contents of a list view.The search bar should be on top of list view and it should hide from user when he scroll down the list view. And when he is searching for something , it should always be on top of list view!!! How can I implement it. Best Regards!

Это было полезно?

Решение

I assume you know how to create XML layout with SearchView on top of a ListView, it could be placed inside vertical LinearLayout. The tricky part is how to manipulate SearchView, right?

You can register a listener on your ListView like this:

    listView.setOnScrollListener(new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case SCROLL_STATE_IDLE:
                    //scroll was stopped, let's show search bar again
                    break;
                case SCROLL_STATE_TOUCH_SCROLL:
                    //user is scrolling, let's hide search bar
                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (firstVisibleItem > 0) {
                //user scrolled down, first element is hidden
            }

        }
    });

As you can see, you will be informed about state changes and you can use it if you want hide searchview during touch events. Or, you can listen for changing visible elements. This simple if statement checking firstVisibleItem > 0 will tell you when user scrolled down. You can also track disappearing list items and react whenever any item is shown or hidden.


Another way to listen for scroll changes is extending ListView and override onScrollChanged() method e.g.

class MyListView extends ListView {

    public MyListView(Context context) {
        super(context);
    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        for (Callbacks c : mCallbacks) {
            c.onScrollChanged(l - oldl, t - oldt);
        }
    }

    @Override
    public int computeVerticalScrollRange() {
        return super.computeVerticalScrollRange();
    }

    public void addCallbacks(Callbacks listener) {
        if (!mCallbacks.contains(listener)) {
            mCallbacks.add(listener);
        }
    }

    public static interface Callbacks {
        public void onScrollChanged(int deltaX, int deltaY);
    }
}

Google folks did something like it in IOSched app.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top