private void setupRecyclerView() { if (itemList == null) { itemList = createItemList(); } adapter = new StaggeredGridLayoutAdapter(this, footerView); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); SpacesItemDecoration decoration = new SpacesItemDecoration((int) getResources().getDimension(R.dimen.item_decoration)); recyclerView.setLayoutManager(layoutManager); recyclerView.addItemDecoration(decoration); adapter.setHeader(new HeaderObject("header")); // header can be null adapter.setItems(itemList); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener( new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager(); int[] lastVisibleItem = manager.findLastCompletelyVisibleItemPositions(null); int spanCount = manager.getSpanCount(); int totalItemCount = manager.getItemCount(); if (lastVisibleItem[spanCount - 1] == (totalItemCount - 1)) { loadMore(); } } } }); }
private void addRefreshItem() { if (itemList != null) { itemList.add(0, new ItemObject("refreshed two")); itemList.add(0, new ItemObject("refreshed one")); int insertPos = adapter.hasHeader() ? 1 : 0; adapter.notifyItemRangeInserted(insertPos, 2); if (!adapter.hasHeader()) { recyclerView.smoothScrollToPosition(0); } onRefreshSucced("refresh succeed"); return; } onRefreshFailed("refresh failed"); }
private void addLoadItem() { if (itemList != null) { itemList.add(new ItemObject("loaded one")); itemList.add(new ItemObject("loaded two")); itemList.add(new ItemObject("loaded three")); itemList.add(new ItemObject("loaded four")); onLoadmoreSucced("load succeed"); adapter.notifyItemRangeInserted(itemList.size() - 1, 4); return; } onLoadmoreFail("load failed"); }