Search code examples
androidlistviewonscroll

onScroll() issue (executed three times)


In this code snippet, when scrolling comes to the end of list, method Log.d() executed 3 times. Why does it happen and how to detect end of list to execute method only once?

Snippet:

public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {
    if (getIntent().getBooleanExtra("isFavorites", false) == false) {
        try {
            if (visibleItemCount > 0 && firstVisibleItem + visibleItemCount == totalItemCount) {
                Log.d(TAG, "Adding to list");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Solution

  • You could implement a boolean variable to ensure execution of the if statement only once.

    boolean executed = false;
    

    and

    if(visibleItemCount > 0 
        && firstVisibleItem + visibleItemCount == totalItemCount 
        && !executed)
    {
        executed = true;
    }