Hide and show the header of a listview when scrolled

Asked

Viewed 569 times

1

I’m developing a app for Android using Android Studio, and want a listview with header where the header is hidden when the list is scrolled down, and it appears when scrolled up regardless of the position of the scroll bar. This mechanism exists on the screen feeds of Facebook as an example.

2 answers

1

You can create a view as a header from your list, and by recognizing the scroll, hide/show that view.

final HeaderView header = new HeaderView(getActivity(), json);
mListView.addHeaderView(header);
setOnScrollListener(new OnScrollListener(){
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        // TODO Auto-generated method stub
    }
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub

        if(scrollState == 0) {
            Log.i("a", "scrolling stopped...");

            if (view.getId() == mListView.getId()) {
                final int currentFirstVisibleItem = mListView.getFirstVisiblePosition();
                if (currentFirstVisibleItem > mLastFirstVisibleItem) {
                    header.setVisibility(View.VISIBLE);
                } else if (currentFirstVisibleItem < mLastFirstVisibleItem) {
                    header.setVisibility(View.GONE)
                }
                mLastFirstVisibleItem = currentFirstVisibleItem;
            } 
        }
     }
 });
  • This answer is not the exact solution to the problem, but it is very close. I used the described methods to change the margin a Frame/Header out of the list, causing it to hide when rolled up, and appearing when rolled down. It didn’t work precisely because the margin change only occurs when the first visible item changes. I want something more precise. I tried to use getScrollY and getPositionScrollBar but only returns 0. Not yet this as I want.

0

You create a view that will be your header and gives an addHeaderView:

    HeaderView header = new HeaderView(getActivity(), json);
    mListView.addHeaderView(header);
  • 0 addHeaderView method asks for a View as parameter, not a Headerview. And where does "json" come from. Create a View for the header and set null in place of Jason, assign and work, but the effect you explain in the question does not appear. You can give more details?

  • Friend, any kind of view (screen element) descends from View, so the @paulokhouri response.

  • Yes, I had suspected. The statement of a type Headerview could need a library that I do not know and that would give the effect that I need. But the main item of the question is still unsolved. That’s why I asked for more details.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.