Android ListView add items to top without list view scroll

This question already has an answer here:

  • Retaining position in ListView after calling notifyDataSetChanged

    6 answers

  • Checking Wi-Fi enabled or not on Android
  • How to support all the different resolutions of android products
  • Camera onPreviewFrame not called
  • ViewPager.setOffscreenPageLimit(0) doesn't work as expected
  • Android AdMob memory usage
  • Show status bar in Android in PhoneGap app (ie prevent fullscreen)
  • Related posts:

    How to check if Receiver is registered in Android?
    android: changing option menu items programmatically
    Android: Cancel Async Task
    What is the size limit for Logcat and how to change its capacity?
    Adding Google Guava to Android project - significantly slows down the build
    Android Studio ProGuard does not appear to run
  • Updating an ongoing notification quietly
  • Android Studio Gradle Build takes more than 5 minutes
  • ListView whose id attribute is '' Error when I have the ListView id set correctly
  • Error Loading Project: Cannot load 3 facets Details
  • ACTION OPEN DOCUMENT TREE only returns empty Recent folder
  • How to make an Android app without using Android Studio?
  • 3 Solutions collect form web for “Android ListView add items to top without list view scroll”

    I have found solution here Retaining position in ListView after calling notifyDataSetChanged

    Sorry for duplicate question.
    The final code is this:

        int index = this.commentsListView.getFirstVisiblePosition() + comments.size();
        View v = this.commentsListView.getChildAt(commentsListView.getHeaderViewsCount());
        int top = (v == null) ? 0 : v.getTop();         
        this.commentsListView.setSelectionFromTop(index, top);

    May be this is what you are looking for:


    “This makes list automatically scroll to the bottom when a data set change notification is received and only if the last item is already visible on screen.” – as quoted here

    Also have a look at ListView’s method public void setSelection (int position). After you added new comments, and notified your adapter, you can use it to keep the current item selected.

    // Get the current selected index
    int previousSelectedIndex = yourListView.getSelectedItemPosition();
    // Change your adapter
    // Determine how many elements you just inserted
    int numberOfInsertedItems = comments.size();
    // Update the selected position
    yourListView.setSelection(previousSelectedIndex + numberOfInsertedItems);

    NOTE: Code is untested. Good luck

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.