向下滚动并更新ListView

时间:2019-02-04 11:27:11

标签: android listview

当我向下滚动ListView(在最后一个项目上)时,我想更新ListView

mConnectionList.setOnScrollListener(new AbsListView.OnScrollListener() {

            private int mLastFirstVisibleItem;
            private boolean isScrollingDown = false;
            private int mLastVisibleItem;

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

                int lastInScreen = firstVisibleItem + visibleItemCount;

                Log.e("lastInScreen", "lastInScreen " + lastInScreen);
                if (mLastFirstVisibleItem <= firstVisibleItem) {
                    Log.i("SCROLLING DOWN", "TRUE");
                    isScrollingDown = false;
                }else{
                    isScrollingDown = true;
                }
                if (mLastFirstVisibleItem > firstVisibleItem) {
                    Log.i("SCROLLING DOWN", "FALSE");
                    isScrollingDown = true;
                }
                mLastFirstVisibleItem = firstVisibleItem;
                mLastVisibleItem = lastInScreen;

            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

                int sizeList = connectionList.size();
                Log.e("lastVisible", " last " + mLastVisibleItem + " " + isScrollingDown);
                if (!isScrollingDown && mLastVisibleItem == sizeList) {
                    getConnections();
                }

            }
        });

这会导致更新我的ListView,然后我向下滚动我的listView,但是当我向上滚动时(位于listView的末尾),我的ListView正在更新

1 个答案:

答案 0 :(得分:0)

您可以实现自定义组件:

public class EndlessListView extends ListView implements OnScrollListener {
  ..
  @Override
  public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
     ...
  }

  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {}
}

在onScroll中,您可以实现更新逻辑:

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

   if (getAdapter() == null)
     return ;

   if (getAdapter().getCount() == 0)
    return ;

  int l = visibleItemCount + firstVisibleItem;
  if (l <= totalItemCount && !isLoading) {
     // It is time to add new data. We call the listener
     this.addFooterView(footer);
     isLoading = true;
     listener.loadData();
  }
}

您可以自定义ListView页脚以通知更新过程:

public void setLoadingView(int resId) {
LayoutInflater inflater = (LayoutInflater) super.getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
footer = (View) inflater.inflate(resId, null);
this.addFooterView(footer);
}

希望这会对您有所帮助。 您可以在我的blog post

中找到所有源代码。