项目中有这么一个需求,收银机的支付方式选择页:
需求具体分析:
每页最多有12种支付方式。
1、支付方式不满1页,就将所有支付展示在第一页。
2、支付方式超过12个,就将第一页右下角的位置变为翻页按钮,将第二页的左下角位置添加一个上一页按钮。超过两页以此类推。
代码实现:
布局很简单:外层是一个RecyclerView,item同样是一个RecyclerView
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_pay_way"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" />
java代码:
PayWayPageAdapter payWayPageAdapter = new PayWayPageAdapter(getActivity(), assemblePayWays(), R.layout.XXX);
payWayRecyclerView.setLayoutManager(layoutManager);
payWayRecyclerView.setAdapter(payWayPageAdapter);
关键代码就是assemblePayWays()这个方法:
private List<PayWayPageEntity> assemblePayWays() {
int total = payWayEntities.size();
//每个页面的格子数
int pageSize = 12;
//找出一共需要几页
for (int i = 1; i < Integer.MAX_VALUE; i++) {
if (i == 1 && 0 < total && total <= pageSize) {
page = 1;
break;
} else if ((pageSize - 2) * (i - 1) + 2 < total && total <= (pageSize - 2) * i + 2) {
page = i;
break;
}
}
//将上一页 下一页插入到合适的位置
List<PayWayEntity> preList = new ArrayList<>();
for (int i = 0; i < page * pageSize; i++) {
if (i < (page - 1) * pageSize && (i + 1) % pageSize == 0) {
preList.add(new PayWayEntity("下一页"));
} else if (i > pageSize && (i + 3) % pageSize == 0) {
preList.add(new PayWayEntity("上一页"));
} else {
preList.add(new PayWayEntity());
}
}
int offset = 0;
for (int i = 0; i < total; i++) {
if ((i + offset > pageSize && (i + offset + 3) % pageSize == 0) || (i + offset < (page - 1) * pageSize && (i + offset + 1) % pageSize == 0))
offset += 1;
preList.set(i + offset, payWayEntities.get(i));
}
//封装好数据
List<PayWayPageEntity> entities = new ArrayList<>();
for (int i = 0; i < page; i++) {
List<PayWayEntity> temp;
PayWayPageEntity entity = new PayWayPageEntity();
temp = preList.subList(i * pageSize, (i + 1) * pageSize);
entity.setPayWayLists(temp);
entities.add(entity);
}
return entities;
}
禁止外层的页卡滑动需要重写LayoutManager
public class CustomLinearLayoutManager extends LinearLayoutManager {
//此处我直接设置为不允许滑动,需要时可以使用setScrollEnabled()动态设置
private boolean isScrollEnabled = false;
public CustomLinearLayoutManager(Context context, int orientation) {
super(context, orientation, false);
}
public void setScrollEnabled(boolean flag) {
this.isScrollEnabled = flag;
}
@Override
public boolean canScrollVertically() {
//Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
return isScrollEnabled && super.canScrollVertically();
}
@Override
public boolean canScrollHorizontally() {
return isScrollEnabled && super.canScrollHorizontally();
}
}
Adapter内部代码类似,只是根据不同的支付方式实现不同的点击事件而已:
@Override
public void convert(RecyclerViewViewHolder viewHolder, PayWayPageEntity payWayPageEntity) {
RecyclerView rv = viewHolder.findViewById(R.id.rv);
PayWayAdapter payWayAdapter = new PayWayAdapter(mContext, payWayPageEntity.getPayWayLists(), R.layout.pay_way_item);
rv.setLayoutManager(new CustomLayoutManager(mContext, 3));
rv.setAdapter(payWayAdapter);
切换页卡用下面的方式实现
layoutManager.scrollToPositionWithOffset(currentPage, 0);
最终实现: