1

update

Basically, bbrakenhoff has answered my question but there is just one more thing left to fix. How can I update the contents of my EndlessFeedAdapter (mEndlsFidAdptr)? I need to clear the item and then reload. I'm using the CWAC EndlessAdapater. Is there a trick to clear the contents or would it be easier to just program a method? After this is done the scroll position should be maintaind.


I am getting data from a server and updating my EndlessFeedAdapter when content changes. Each time I am updating my adapter and reloading content. The problem is that after reloading my list jumps right back to the top as my scroll position is not maintained. I have tried setSelection and setSelectionFromTop extensively, but without positive results.

How do I maintain scroll position after the adapter has been updated?

I have been going through the forums searching for an answer but nothing seems to be working.

I have tried all these: Maintain/Save/Restore scroll position when returning to a ListView

This didn't work:

int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();


 // restore index and position
mList.setSelectionFromTop(index, top);

Nor this:

// Save ListView state
Parcelable state = listView.onSaveInstanceState();

// Set new items
listView.setAdapter(adapter);

// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);

Nor the other solutions such as setting up a runnable or setting the scrollPositionY. Setting notifyDataChanged didn't work as I am loading from different lists.

My code:

private void showFeed() {

    if (mFeedActivity.mInFeed) {
        mQuickReturnView.setVisibility(View.VISIBLE);
    } else {
        mQuickReturnView.setVisibility(View.GONE);
    }                                  

    Activity actvt= getActivity();
    if (actvt == null || mFeedListView == null) return;

    actvt.invalidateOptionsMenu();

    mFeedListView.setVisibility(View.VISIBLE);

    //updated with help from response
    if (mAdapter == null){
        mAdapter = new FeedAdapter(actvt, 0, mFeed.getItems().getFeedItemList(), this);
    } else {
        mAdapter.clear();
        mAdapter.addAll(mFeed.getItems().getFeedItemList());
        mAdapter.notifyDataSetChanged();
    }

    mEndlsFidAdptr = new EndlessFeedAdapter(actvt, mAdapter, R.layout.progress_row, mFeed.isShowMoreBar(),

    mEndlsFidAdptr.setRunInBackground(false);

    //Parcelable state = mFeedListView.onSaveInstanceState();
    mFeedListView.setAdapter(mEndlsFidAdptr);
    //mFeedListView.onRestoreInstanceState(state);



    mFeedListView.setSelectionFromTop(mFirstVisibleItem, mVisibleItemOffset);

    if(!(mFeedScope.equalsIgnoreCase(FeedScope.BOOKMARKS.xmlValue()) ||
            mFeedScope.equalsIgnoreCase(FeedScope.DOCUMENT.xmlValue()) ||
            mFeedScope.equalsIgnoreCase(FeedScope.NOTIFICATIONS.xmlValue()) ||
            mFeedScope.equalsIgnoreCase(FeedScope.RECEIVED_TASKS.xmlValue()) ||
            mFeedScope.equalsIgnoreCase(FeedScope.SEND_TASKS.xmlValue()))) {

  mFeedListView.getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);


        mFeedListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                mCanShowHide = scrollState == SCROLL_STATE_FLING;

            }


            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                View v = mFeedListView.getChildAt(0);
                //View v = null;
                if(!mFeedActivity.mInFeed || v == null)
                    return;

                int top = v.getTop();

                if(mIsAnimating) {
                    mVisibleItemOffset = top;
                    mFirstVisibleItem = firstVisibleItem;
                    return;
                }

                boolean hide = false;
                boolean show = false;
                float stickyHeight = getResources().getDimension(R.dimen.sticky_height);

                if(firstVisibleItem == mFirstVisibleItem) {
                    if((top + stickyHeight) < mVisibleItemOffset) {
                        // Content scrolled down
                        // if shown then hide quickactionview
                        if(mQuickReturnShown) {
                            hide = true;
                        }

                    } else if (top > mVisibleItemOffset) {
                        // Content scrolled up
                        // if hidden then show quickactionview
                        if(!mQuickReturnShown) {
                            show = true;
                        }

                    }

                } else if(firstVisibleItem > mFirstVisibleItem) {
                    // Content scrolled down
                    // if shown then hide quickactionview
                    if(mQuickReturnShown) {
                        hide = true;
                    }

                } else if (firstVisibleItem < mFirstVisibleItem) {
                    // Content scrolled up
                    // if hidden then show quickactionview
                    if(!mQuickReturnShown) {
                        show = true;
                    }
                }

                if((show && mCanShowHide) || (top == 0 && !mQuickReturnShown)) {
                    mTranslateAnimation = new TranslateAnimation(0, 0, -mQuickReturnHeight, 0);
                    mTranslateAnimation.setDuration(DURATION_MILLIS);
                    mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                            mIsAnimating = true;
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            mIsAnimating = false;
                            mQuickReturnShown = true;
                            mQuickReturnView.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });

                    mQuickReturnView.startAnimation(mTranslateAnimation);
                }

                if(hide) {
                    mTranslateAnimation = new TranslateAnimation(0, 0, 0, -mQuickReturnHeight);
                    mTranslateAnimation.setDuration(DURATION_MILLIS);
                    mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                            mIsAnimating = true;
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            mIsAnimating = false;
                            mQuickReturnShown = false;
                            mQuickReturnView.setVisibility(View.GONE);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) { }
                    });


                    mQuickReturnView.startAnimation(mTranslateAnimation);
                }

                mVisibleItemOffset = top;
                mFirstVisibleItem = firstVisibleItem;
            }
        });
    } else {
        mFeedListView.setOnScrollListener(null);

    }

    mFeedListView.setSelectionFromTop(mFirstVisibleItem, mVisibleItemOffset);

    //mFeedListView.scrollTo(mCurrentX,mCurrentY);

    if(mFeed.getItems().getFeedItemList().size() == 0) {
        mEmptyFeedView.setVisibility(View.VISIBLE);
    }
}
4
  • are you try to use getScrollPosition and then set scrollPOsition?
    – MHP
    Aug 18, 2014 at 12:39
  • Yes, I have tried to set the scroll position in the onScroll method and then call scrollTo at the end of the method (you can see the implementation commented out) Aug 18, 2014 at 12:51
  • where do you add newitems?
    – mmlooloo
    Aug 18, 2014 at 13:05
  • They are added with the call - mFeed.getItems().getFeedItemList(). This makes a call to my rest service. Aug 18, 2014 at 14:06

3 Answers 3

2

Are you calling the method showFeed() everytime you received new data? If yes, then maybe you could try to refill the adapter instead of assigning a new one every time.

I don't know exactly what you are doing in your adapter, so I'll show you how I did it in one of my apps.

In my Activity/Fragment I do this when I want to update the list with new items:

private void refreshCalendar(ArrayList<CalendarDay> newCalendar) {
    if (mAdapter == null) {
        mAdapter = new CalendarAdapter(getActivity(), newCalendar);
        mExpandableListView.setAdapter(mAdapter);
    }
    else {
        mAdapter.refill(newCalendar);
    }

    restoreInstanceState();
}

And in the adapter:

public void refill(ArrayList<CalendarDay> newCalendar) {
    mCalendar.clear();
    mCalendar.addAll(newCalendar);
    notifyDataSetChanged();
}
3
  • I won't downvote you because I'm in the same boat :) So add mEndlsFidAdaptr.notifyDataChanged() if it is not empty? This works except that I'm using multiple fragments, which then don't refresh after this implementation... Aug 18, 2014 at 13:18
  • You just jumped me in points! I meant .notifyDataSetChanged(), which then loads the exact same list even when switching to another fragment. Aug 18, 2014 at 13:31
  • With the help from bbrakenhoff, I was able to use adapt his code in my case to not create a new adapter after a refresh. However, my code still gets thrown to a looper after which it gets reset to the top of the screen. Any ideas? Aug 19, 2014 at 6:37
1

Maybe you could try and remove this line?

  mFeedListView.setSelectionFromTop(mFirstVisibleItem, mVisibleItemOffset);

Edit: You are using this line twice in your code.

Edit: In the code in your question you are only refreshing mAdapter and not mEndlsFidAdptr . That one is still assigned a new one. Everytime you assign a new adapter to you ListView it scrolls back to the top.

6
  • No, that is not it. I have not only removed .setSelectionFromTop from one position, but also both positions and my scroll position still gets reset... Aug 19, 2014 at 7:39
  • Yup, that is the problem. I just can't seem to clear out the mEndlsFidAdptr and then update it like the mAdapter. I can only notifyDataSetChanged without actually adding to it... Any ideas how to add the second adapter without using .clear? Aug 19, 2014 at 8:42
  • Why can't you clean it then? Are you using an array, or List? Aug 19, 2014 at 8:48
  • It is actually the same mFeed.getItems().getFeedItemList() that the mAdapter uses, so it is a List. I already did .clear on that list though... Aug 19, 2014 at 10:14
  • Are you getting an exception when doing that? Because if you have something like List<FeedItem> you cannot modify it. You need to have an ArrayList<FeedItem>. Aug 19, 2014 at 10:24
0

So the solution wasn't the logical place where I was looking. Thanks a lot to bbrakenhoff for pointing me in the right direction!

My class showFeed() was called from another class called downloadFeed() my scroll position wasn't maintained because downloadFeed() was only loading 5 items when it refreshed, hence even if I maintained the correct scroll position it was not visible.

Although it may be a long shot if someone else has this problem - to fix simply create a variable to hold the total size of your scrollable list when the user performs an onClick event. Then when downloadFeed() is called again, there are more items to download instead the default 5. Then the scroll position is able to be maintained as the visible items are now present.

I ended up using mFeedListView.setSelectionFromTop(firstVisibleItem, positionOffset)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.