仿探探层叠布局

技术点

1.在不触摸屏幕的情况下,卡片呈现层叠布局。


仿探探层叠布局_第1张图片
Paste_Image.png

2.拖拽时,下层的布局随最上层卡片的位置放大或缩小

层叠布局

static int MAX_COUNT=4;//最大可视view数
主要重写LayoutManager的onLayoutChildren()方法,重新排列item的位置

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);
        //在布局之前,将所有的子View先Detach掉,放入到Scrap缓存中
        detachAndScrapAttachedViews(recycler);
        int itemCount = getItemCount();//子view总数
        //getChildCount() 被回收的不计算在内
        for (int i = 0; i < itemCount; i++) {
            //从缓存中取出
            View view = recycler.getViewForPosition(i);
            addView(view);
            measureChildWithMargins(view,0,0);
            int width=getDecoratedMeasuredWidth(view);
            int height=getDecoratedMeasuredHeight(view);
            layoutDecoratedWithMargins(view,0,0,width,height);
            if (i>itemCount-MAX_COUNT-1){//i=6,7,8,9.在最上层的四个
                view.setScaleX(1-(itemCount-i-1)*0.05f);
                view.setTranslationY((itemCount-i-1)*30);//每次多向下平移30px
            }else{
                //除了最上面四个外,其他的大小都与从上面数第四个一样大
                view.setScaleX(1-(MAX_COUNT-1)*0.05f);
                view.setTranslationY((MAX_COUNT-1)*30);
            }
        }
    }

滑动效果

重写ItemTouchHelper.Callback的onChildDraw()方法,此方法用于实时绘制子view。

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                            float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        int itemCount = recyclerView.getChildCount();
        double fraction = Math.sqrt(dX * dX + dY * dY) / recyclerView.getWidth();
        float fractionX=dX/recyclerView.getWidth()/2;
        for (int i = 0; i < itemCount; i++) {
            View view = recyclerView.getChildAt(i);
            if (i == itemCount - 1) {
                view.setRotation(fractionX*30);
            } else {
                if (i > ]MAX_COUNT-1) {
                    view.setScaleX((float) (1 - (itemCount - i - 1) * 0.05f + 0.05f * fraction));
                    view.setTranslationY((float) ((itemCount - i - 1) * 30 - 30 * fraction));
                } else {

                }
            }
        }
    }

代码地址:https://github.com/bitdp/TanTan.git

你可能感兴趣的:(仿探探层叠布局)