1. 程式人生 > >使用ViewPager和RecyclerView實現水平分頁功能

使用ViewPager和RecyclerView實現水平分頁功能

/**
 * ght (c) 2007-2017 xxx Inc. All rights reserved.
 *
 * @author lzz
 *         Created 2017/5/4 10:07
 * @license http://www.xxx.net
 * @link http://www.xxx.net
 * @description 推薦商品的ViewPager介面卡;帶有水平分頁功能的RecyclerView
 *
 * **********************
 *   ##     ##      ##  *
 *                      *
 *   ##     ##      ##  *
 * **********************
 */
public class GoodsPageAdapter extends PagerAdapter { private List<View> indicators = new ArrayList<>();//水平分頁的指示器 private ArrayList<GoodsVo> datas = new ArrayList<>();//RecyclerView資料集合 private Context context; private LinearLayout llIndicators;//水平分頁的容器 public
void setDatas(ArrayList<GoodsVo> datas) { this.datas = datas; } public List<View> getIndicators() { return indicators; } public GoodsPageAdapter(Context context, LinearLayout llIndicators) { this.context = context; this.llIndicators = llIndicators; } /** * 計算水平分頁的數量 * * @return
*/
@Override public int getCount() { int count = datas.size() % 6; int divide = datas.size() / 6; return count == 0 ? divide : divide + 1; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public RecyclerView instantiateItem(ViewGroup container, int position) { RecyclerView recyclerView = new RecyclerView(context); //2行顯示。列數量通過item的寬度來控制,顯示3列 GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(gridLayoutManager); GoodsDetailsHotGridAdapter hotGridAdapter = new GoodsDetailsHotGridAdapter(context); recyclerView.setAdapter(hotGridAdapter); List<GoodsVo> list = new ArrayList<GoodsVo>(); //每頁最多顯示6個,小於資料集總數,且小於下一頁開始的位置索引 for (int i = position * 6; i < (position + 1) * 6 && i < datas.size(); i++) { list.add(datas.get(i)); } //初始化指示器。position == 0只初始化一次;且有多頁; for (int i = 0; position == 0 && getCount() != 1 && i < getCount(); i++) { View indicator = new View(context); Drawable drawable = context.getResources().getDrawable(R.drawable.indicator_selector); indicator.setBackground(drawable); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(24, 24); params.setMarginEnd(10); llIndicators.addView(indicator, params); indicators.add(indicator); } hotGridAdapter.setDatas(list); hotGridAdapter.notifyDataSetChanged(); container.addView(recyclerView); return recyclerView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeViewAt(position); } }