遇到了这麽一个需求,ListView滑到最底,然后会自动在底部加入新的Cell,实现动态刷新。
1. 首先,为ListView加上setOnScrollListener。
lvHomePostItem.setOnScrollListener(new AbsListView.OnScrollListener() { private Integer scrollState; @Override public void onScrollStateChanged(AbsListView view, int scrollState) { this.scrollState = scrollState; switch (scrollState) { // Not scrolling case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: // go to last cell if (view.getLastVisiblePosition() == (view.getCount() - 1) && totalAmountOfLvItem <= 20 ) { addData(); } break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {} });
2. addData()是调用了notifyDataSetChanged。而notifyDataSetChanged是回调ListView来刷新UI,实现动态刷新。
private Integer totalAmountOfLvItem = 0; private Integer getExtraNumberOfPost = 2; private String getHotPostByCursor; private String getPostResult; private List<PostDTO> postExtraDTOs = new ArrayList<PostDTO>(); private ArrayList<Bitmap> bitExtraMaps = new ArrayList<Bitmap>(); private void addData() { popupLoadingWindow(); // Network thread new Thread(new Runnable() { @Override public void run() { totalAmountOfLvItem = postAdapter.getCount(); // clear list if ( !postExtraDTOs.isEmpty()) { postExtraDTOs.clear(); } if ( !bitExtraMaps.isEmpty()) { bitExtraMaps.clear(); } // get extra post getHotPostByCursor = Configuration.getHotPostByCursor(totalAmountOfLvItem, getExtraNumberOfPost); getPostResult = okhttp.getResponse(getHotPostByCursor); postExtraDTOs = gsonTools.getPost(getPostResult); totalAmountOfLvItem += getExtraNumberOfPost; // get extra bitmap for ( int i = 0; i < postExtraDTOs.size(); i++ ) { Bitmap temp = bitMap.returnBitMap(postExtraDTOs.get(i).getAbstractImg()); bitExtraMaps.add(temp); } // UI thread getActivity().runOnUiThread(new Runnable() { @Override public void run() { // set extra post & bitmap into ListView Data for ( int i = 0; i < postExtraDTOs.size(); i++ ) { postHotDTOs.add(postExtraDTOs.get(i)); bitHotMaps.add(bitExtraMaps.get(i)); } postAdapter.notifyDataSetChanged(); lvHomePostItem.setSelection(postAdapter.getCount()-1); dismissPopupLoadingWindow(); } }); } }).start(); }
就这样实现动态刷新。