Android Endless List

后端 未结 10 1297
梦如初夏
梦如初夏 2020-11-22 02:52

How can I create a list where when you reach the end of the list I am notified so I can load more items?

10条回答
  •  执笔经年
    2020-11-22 03:21

    You can detect end of the list with help of onScrollListener, working code is presented below:

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (view.getAdapter() != null && ((firstVisibleItem + visibleItemCount) >= totalItemCount) && totalItemCount != mPrevTotalItemCount) {
            Log.v(TAG, "onListEnd, extending list");
            mPrevTotalItemCount = totalItemCount;
            mAdapter.addMoreData();
        }
    }
    

    Another way to do that (inside adapter) is as following:

        public View getView(int pos, View v, ViewGroup p) {
                if(pos==getCount()-1){
                    addMoreData(); //should be asynctask or thread
                }
                return view;
        }
    

    Be aware that this method will be called many times, so you need to add another condition to block multiple calls of addMoreData().

    When you add all elements to the list, please call notifyDataSetChanged() inside yours adapter to update the View (it should be run on UI thread - runOnUiThread)

提交回复
热议问题