RecyclerView 实现柱状图和折线图

先上要实现的效果图


Paste_Image.png

整体布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"

    android:background="@color/comm_white"
    android:layout_height="match_parent">
    <TextView
        android:layout_marginTop="24dp"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="16dp"
        android:layout_width="wrap_content"
        android:text="价格走势"
        android:textSize="18sp"
        android:textColor="@color/font_black_color"
        android:layout_height="wrap_content" />

    <include layout="@layout/layout_pop_menu_item_splite" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="挂牌均价"
            android:textSize="12sp"
            android:drawableLeft="@drawable/shape_chart_fold"
            android:drawablePadding="6dp"
            />
        <TextView
            android:layout_marginLeft="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="成交量(套)"
            android:textSize="12sp"
            android:drawableLeft="@drawable/shape_chart_bar"
            android:drawablePadding="6dp"
            />
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:background="#eee"
        android:id="@+id/recyclerView"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_width="match_parent"
        android:layout_height="220dp"></android.support.v7.widget.RecyclerView>
</LinearLayout>

item的布局,也即柱状图的布局,改变TextView的高度来实现柱状图,外面套一个LinearLayout一是方便底部对齐,二是,方便点击列时,出现选中效果。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_marginBottom="20dp"
    android:gravity="bottom"
    android:layout_height="200dp">

    <TextView
        android:id="@+id/tv_value"
        android:layout_width="16dp"
        android:background="#94B1D3"
        android:layout_height="wrap_content" />
</LinearLayout>

对数据进行处理,找出最大值,和高度的比例关系

    private double maxValue = 0;
    /**
     * 值和高度的对应比例
     */
    private double scale = 1;
    //总高-横轴坐标高度(后面已经转换为px了)
    private int maxHeith = 220 - 20;

    private int selIndex = -1;

    //处理recyclerView上的事件,点击外面的时候去掉item的选中状态
    private GestureDetectorCompat mGestureDetectorCompat;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataEntities = new DataEntity[12];
        for (int i = 0; i < dataEntities.length; i++) {
            dataEntities[i] = new DataEntity(i, i * 10 + 10, i * 10 + 5);
            maxValue = Math.max(maxValue, Math.max(dataEntities[i].barValue, dataEntities[i].foldValue));
        }
        //刻意放大一点,避免最大值顶部不好描点
        maxValue = Math.ceil(maxValue * 11) / 10;
        //将dp换算为PX,避免后面再转换
        maxHeith = PxUtils.dpToPx(maxHeith, getContext());
        scale = maxHeith / maxValue;
       
    }

配置recyclerView的适配器和ItemDecoration

 recyclerView.setAdapter(new MRcyViewAdapter());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        recyclerView.addItemDecoration(new MChartItemDecoration());

适配器的处理,主要通过控制高度,实现柱状图效果,折线图通过ItemDecoration绘制实现

    private class MRcyViewAdapter extends RecyclerView.Adapter<MViewHolder> {

        @Override
        public MViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_mp_chart, parent, false);
            return new MViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(final MViewHolder holder, final int position) {
            DataEntity dataEntity = dataEntities[position];
            holder.tv_value.setHeight((int) (dataEntity.barValue * scale));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selIndex = position;
//                    notifyItemChanged(selIndex);
                    notifyDataSetChanged();
                }
            });
        }

        @Override
        public int getItemCount() {
            return dataEntities.length;
        }
    }

来来来,看看强大的ItemDecoration

class MChartItemDecoration extends RecyclerView.ItemDecoration {


        int itemMargin = PxUtils.dpToPx(18, getContext());
        int xTextsize = PxUtils.spToPx(12, getContext());
        int radiusOvil = PxUtils.dpToPx(4, getContext());
        int lineWidth = PxUtils.dpToPx(2, getContext());
        int xColor = Color.parseColor("#999999");
        int ovilColor = Color.parseColor("#F15824");
        int selColor = Color.parseColor("#0B6286");
        int popColor = Color.parseColor("#e5343C45");

        int popLeftMargin = PxUtils.dpToPx(10, getContext());
        int popTopMargin=PxUtils.dpToPx(16, getContext());
        int popItemMargin = PxUtils.dpToPx(6, getContext());
        int popOffset=PxUtils.dpToPx(16, getContext());
        Paint paint;

        public MChartItemDecoration() {
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setStrokeWidth(lineWidth);
            paint.setTextSize(xTextsize);
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void onDrawOver(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
            super.onDrawOver(canvas, parent, state);
            Log.i("MChartItemDecoration", "onDrawOver: ");

            int childCount = parent.getChildCount();
            int preX = 0;
            int preY = 0;
            for (int i = 0; i < childCount; i++) {
                View childAt = parent.getChildAt(i);
                int px = childAt.getLeft() + childAt.getWidth() / 2;
                int py = parent.getHeight();//在RecyclerView的底部绘制,坐标系以RecyclerView的区域为参考
                //绘制X轴坐标
                paint.setColor(xColor);
                drawXValue(canvas, paint, (parent.getChildLayoutPosition(childAt) + 1) + "月", px, py);
                DataEntity dataEntity = dataEntities[parent.getChildLayoutPosition(childAt)];
                py = (int) (maxHeith - dataEntity.foldValue * scale);

                //绘制圆圈
                paint.setColor(ovilColor);
                canvas.drawOval(new RectF(px - radiusOvil, py - radiusOvil, px + radiusOvil, py + radiusOvil), paint);
                if (i > 0) {
                    canvas.drawLine(preX, preY, px, py, paint);
                }
                //记录当前的圆圈的坐标点,避免画线的时候再计算
                preX = px;
                preY = py;

            }
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.set(itemMargin, 0, itemMargin, 0);
        }
    }
    
        private void drawXValue(Canvas canvas, Paint paint, String value, int pX, int pY) {
        Rect rect = new Rect();
        paint.getTextBounds(value, 0, value.length(), rect);
        paint.setTextAlign(Paint.Align.CENTER);
        //centerY是负数
        canvas.drawText(value, pX, pY + rect.centerY(), paint);
    }

getItemOffsets 设置item柱状图 左右的间距。

onDrawOver 绘制的参考坐标区域是RecyclerView的区域,所以会在底部绘制X坐标(月份),然后绘制圆圈,连接线。
这里可以看出柱状图及item方便我们定位X轴的坐标,而RecyclerView本身的封装能简化我们对滚动的处理以及事件区域的检测。若自定义,要处理滚动,以及点击事件是否在柱状区域的判断,很多逻辑。而用RecyclerView不用考虑这么多,而且能有很好的复用。

Paste_Image.png

添加选中的竖线

 @Override
        public void onDrawOver(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
            super.onDrawOver(canvas, parent, state);
            Log.i("MChartItemDecoration", "onDrawOver: ");
//            Rect targetRect = new Rect(50, 50, 1000, 200);

            int childCount = parent.getChildCount();
            int preX = 0;
            int preY = 0;
            for (int i = 0; i < childCount; i++) {
                View childAt = parent.getChildAt(i);
                int px = childAt.getLeft() + childAt.getWidth() / 2;
                int py = parent.getHeight();//在RecyclerView的底部绘制,坐标系以RecyclerView的区域为参考
                //绘制X轴坐标
                paint.setColor(xColor);
                drawXValue(canvas, paint, (parent.getChildLayoutPosition(childAt) + 1) + "月", px, py);
                DataEntity dataEntity = dataEntities[parent.getChildLayoutPosition(childAt)];
                py = (int) (maxHeith - dataEntity.foldValue * scale);

                if (selIndex == parent.getChildLayoutPosition(childAt)) {
                    //如果被选中,画一条竖线
                    paint.setColor(selColor);
                    canvas.drawLine(px,0,px,maxHeith,paint);
                   
                }

                //绘制圆圈
                paint.setColor(ovilColor);
                canvas.drawOval(new RectF(px - radiusOvil, py - radiusOvil, px + radiusOvil, py + radiusOvil), paint);
                if (i > 0) {
                    canvas.drawLine(preX, preY, px, py, paint);
                }
                //记录当前的圆圈的坐标点,避免画线的时候再计算
                preX = px;
                preY = py;

            }

检查到当前item是选中的,则绘制一条竖线。

  • 选中柱状所在的真个竖直区域(LinearLayout),都显示竖线
  • 点击外围区域 竖线消失
  • 滑动的时候竖线还保持

来看选中item的代码

在Adapter中设置点击事件时,更新selIndex ,同时通知刷新界面

注意notifyItemChanged(selIndex)系统默认会添加一个动画,柱状图会明显的“抖动”有重新绘制的感觉,故没有用它。

 @Override
        public void onBindViewHolder(final MViewHolder holder, final int position) {
            DataEntity dataEntity = dataEntities[position];
            holder.tv_value.setHeight((int) (dataEntity.barValue * scale));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selIndex = position;
//                    notifyItemChanged(selIndex);
                    notifyDataSetChanged();
                }
            });
        }

点击外围,竖线消失,需要判断事件是在item上面,还是RecyclerView上,尝试过给RecyclerView设置onclickLisener,但是没有响应。

于是给RecyclerView添加OnTouchLisener,因为我们知道如果子view不处理或者没接受事件,事件默认会交个父控件(RecyclerView)的onTouch来处理。

        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mGestureDetectorCompat.onTouchEvent(event);
                return false;
            }
        });

添加OnTouchListener 并将事件交个GestureDetectorCompat 来处理,这样就能简化我们自己去判断事件是点击还是滑动。

mGestureDetectorCompat = new GestureDetectorCompat(getActivity(),new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                selIndex = -1;
                recyclerView.getAdapter().notifyDataSetChanged();
                return super.onSingleTapUp(e);
            }
        });

是点击,则清空selIndex 并通知刷新。

Paste_Image.png

接下来看看头疼的选中后的浮框实现。

if (selIndex == parent.getChildLayoutPosition(childAt)) {
                    //如果被选中,画一条竖线
                    paint.setColor(selColor);
                    canvas.drawLine(px, 0, px, maxHeith, paint);
                    drawPopWin(canvas, px, py, dataEntity);
    }
                



int popHorizontarMargin = PxUtils.dpToPx(10, getContext());
        int popTopMargin = PxUtils.dpToPx(16, getContext());
        int popVerctorMargin = PxUtils.dpToPx(8, getContext());
        int popOffset = PxUtils.dpToPx(16, getContext());
        String foldStr = "挂牌均价";
        String barStr = "成交量";
        //两个标题的字体大小一样,就长度不一样,就没必要创建两个Rect浪费了
        Rect rectTitle= new Rect();
        //浮框左边标题的最大宽度
        int maxPopTitleWidth = 0;
        Paint paint;

        public MChartItemDecoration() {
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setStrokeWidth(lineWidth);
            paint.setTextSize(xTextsize);

            paint.getTextBounds(foldStr, 0, foldStr.length(), rectTitle);
            maxPopTitleWidth = Math.max(maxPopTitleWidth, rectTitle.width());
            paint.getTextBounds(barStr, 0, barStr.length(), rectTitle);
            maxPopTitleWidth = Math.max(maxPopTitleWidth, rectTitle.width());
        }
 
 
 
 
 private void drawPopWin(Canvas canvas,int px,int py,DataEntity dataEntity) {
            paint.setColor(popColor);
            paint.setStyle(Paint.Style.FILL);
            int maxValueWidth=0;
            Rect rectVlaue = new Rect();
            String foldValue = dataEntity.foldValue + "";
            String barValue = dataEntity.barValue + "";
            paint.getTextBounds(foldValue, 0, foldValue.length(), rectVlaue);
            maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());
            paint.getTextBounds(barValue, 0, barValue.length(), rectVlaue);
            maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());

            //计算 浮框的宽度
            int popWidth = popHorizontarMargin * 2 + maxPopTitleWidth + maxValueWidth + popHorizontarMargin;
            int popHeight = popTopMargin * 2 + rectTitle.height() + popVerctorMargin + rectVlaue.height();
            int popX = px + popOffset;
            int popY = py + popOffset;
            //画浮框区域
            canvas.drawRect(popX, popY, popX + popWidth, popY + popHeight, paint);

            //绘制文字,从右边往坐标绘制,方便右对齐
            paint.setTextAlign(Paint.Align.RIGHT);
            paint.setColor(Color.WHITE);
            paint.setAlpha(178);
            canvas.drawText(foldStr,  popX+popHorizontarMargin + maxPopTitleWidth,popY+popTopMargin+rectVlaue.height(), paint);
            canvas.drawText(barStr,  popX+popHorizontarMargin + maxPopTitleWidth,popY+popTopMargin+rectVlaue.height()*2+popVerctorMargin,  paint);

            paint.setTextAlign(Paint.Align.LEFT);
            paint.setAlpha(255);
            canvas.drawText(foldValue,  popX+ popHorizontarMargin + maxPopTitleWidth+popHorizontarMargin,popY+popTopMargin+rectVlaue.height(), paint);
            canvas.drawText(barValue,  popX+ popHorizontarMargin + maxPopTitleWidth+popHorizontarMargin, popY+popTopMargin+rectVlaue.height()*2+popVerctorMargin,paint);
        }
        
        
        
                
Paste_Image.png

接下来处理边界检测的问题,

private void drawPopWin(Canvas canvas,int px,int py,int parentWidth,int parentHeight,DataEntity dataEntity) {
            paint.setColor(popColor);
            paint.setStyle(Paint.Style.FILL);
            int maxValueWidth=0;
            Rect rectVlaue = new Rect();
            String foldValue = dataEntity.foldValue + "";
            String barValue = dataEntity.barValue + "";
            paint.getTextBounds(foldValue, 0, foldValue.length(), rectVlaue);
            maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());
            paint.getTextBounds(barValue, 0, barValue.length(), rectVlaue);
            maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());

            //计算 浮框的宽度
            int popWidth = popHorizontarMargin * 2 + maxPopTitleWidth + maxValueWidth + popHorizontarMargin;
            int popHeight = popTopMargin * 2 + rectTitle.height() + popVerctorMargin + rectVlaue.height();
            int popX = px + popOffset;
            int popY = py + popOffset;

            if (popY + popHeight > parentHeight) {//往上翻
                popY = py - popOffset - popHeight;
            }
            if (popX + popWidth > parentWidth) {//画到左边
                popX = px - popOffset - popWidth;
            }


            //画浮框区域
            canvas.drawRect(popX, popY, popX + popWidth, popY + popHeight, paint);

            //绘制文字,从右边往坐标绘制,方便右对齐
            paint.setTextAlign(Paint.Align.RIGHT);
            paint.setColor(Color.WHITE);
            paint.setAlpha(178);
            canvas.drawText(foldStr,  popX+popHorizontarMargin + maxPopTitleWidth,popY+popTopMargin+rectVlaue.height(), paint);
            canvas.drawText(barStr,  popX+popHorizontarMargin + maxPopTitleWidth,popY+popTopMargin+rectVlaue.height()*2+popVerctorMargin,  paint);

            paint.setTextAlign(Paint.Align.LEFT);
            paint.setAlpha(255);
            canvas.drawText(foldValue,  popX+ popHorizontarMargin + maxPopTitleWidth+popHorizontarMargin,popY+popTopMargin+rectVlaue.height(), paint);
            canvas.drawText(barValue,  popX+ popHorizontarMargin + maxPopTitleWidth+popHorizontarMargin, popY+popTopMargin+rectVlaue.height()*2+popVerctorMargin,paint);
        }
Paste_Image.png
Paste_Image.png

由于滑动过程中,他会一直检测重绘,这里还有两个问题

  • 在靠边的的地方左右滑动,浮框会左右跳跃
  • 在往右侧活动的过程中,若bar被回收了,浮框也会立即没有了,不会随着滑动慢慢的一点点的消失。

当然这两个问题也是可以解决的,炫技到此结束,哈哈。

处理左右跳动问题:

引入另一个标签值,是否改变了选中的索引

    private boolean changeSelIndex = false;

Bitmap tempBitmap;
        Canvas tempCanvas;
        int tempOffsetX = popOffset;
        int tempOffsetY = popOffset;

若索引改变了,那么 当前的浮框内容(tempBitmap)需要重新绘制内容,而且需要检测边界。若索引没有改变,滑动引起的重绘,那么浮框内容不需要重绘,也无需检测边界,只需要在绘制tempBitmap时,改变他在RecyclerView 中的坐标位置即可。
tempOffsetX,tempOffsetY 用于记录上次索引变化,检测边界后,它相对的偏移量,这样就不会由于频繁检测边界,导致偏移变化而引起跳跃。

绘制的逻辑如下

 private void drawPopWin(Canvas canvas, int px, int py, int parentWidth, int parentHeight, DataEntity dataEntity) {
            if (tempBitmap == null || changeSelIndex) {
                tempOffsetX = popOffset;
                tempOffsetY = popOffset;
                int maxValueWidth = 0;
                Rect rectVlaue = new Rect();
                String foldValue = dataEntity.foldValue + "";
                String barValue = dataEntity.barValue + "";
                paint.getTextBounds(foldValue, 0, foldValue.length(), rectVlaue);
                maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());
                paint.getTextBounds(barValue, 0, barValue.length(), rectVlaue);
                maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());

                //计算 浮框的宽度
                int popWidth = popHorizontarMargin * 2 + maxPopTitleWidth + maxValueWidth + popHorizontarMargin;
                int popHeight = popTopMargin * 2 + rectTitle.height() + popVerctorMargin + rectVlaue.height();


                if (py + popOffset + popHeight > parentHeight) {//往上翻
                    tempOffsetY = -popOffset - popHeight;
                }
                if (px + popOffset + popWidth > parentWidth) {//画到左边
                    tempOffsetX = -popOffset - popWidth;
                }

                tempBitmap = Bitmap.createBitmap(popWidth, popHeight, Bitmap.Config.ARGB_8888);
                tempCanvas = new Canvas(tempBitmap);
                tempCanvas.drawColor(popColor);

                //绘制文字,从右边往坐标绘制,方便右对齐
                paint.setTextAlign(Paint.Align.RIGHT);
                paint.setColor(Color.WHITE);
                paint.setAlpha(178);
                tempCanvas.drawText(foldStr, popHorizontarMargin + maxPopTitleWidth, popTopMargin + rectVlaue.height(), paint);
                tempCanvas.drawText(barStr, popHorizontarMargin + maxPopTitleWidth, popTopMargin + rectVlaue.height() * 2 + popVerctorMargin, paint);

                paint.setTextAlign(Paint.Align.LEFT);
                paint.setAlpha(255);
                tempCanvas.drawText(foldValue, popHorizontarMargin + maxPopTitleWidth + popHorizontarMargin, popTopMargin + rectVlaue.height(), paint);
                tempCanvas.drawText(barValue, popHorizontarMargin + maxPopTitleWidth + popHorizontarMargin, popTopMargin + rectVlaue.height() * 2 + popVerctorMargin, paint);
                changeSelIndex = false;
            }
            canvas.drawBitmap(tempBitmap, px + tempOffsetX, py + tempOffsetY, paint);
        }

同时这样效率应该也更好,比较在滑动的时候,浮框的内容不用频繁去绘制了。

再次优化,如果碰到边界,则切换一次位置到对面,但不至于想前面,右边一旦空间富余,浮框就跑回来了。

private void drawPopWin(Canvas canvas, int px, int py, int parentWidth, int parentHeight, DataEntity dataEntity) {
            if (tempBitmap == null || changeSelIndex) {
                tempOffsetX = popOffset;
                tempOffsetY = popOffset;
                int maxValueWidth = 0;
                Rect rectVlaue = new Rect();
                String foldValue = dataEntity.foldValue + "";
                String barValue = dataEntity.barValue + "";
                paint.getTextBounds(foldValue, 0, foldValue.length(), rectVlaue);
                maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());
                paint.getTextBounds(barValue, 0, barValue.length(), rectVlaue);
                maxValueWidth = Math.max(maxValueWidth, rectVlaue.width());

                //计算 浮框的宽度
                int popWidth = popHorizontarMargin * 2 + maxPopTitleWidth + maxValueWidth + popHorizontarMargin;
                int popHeight = popTopMargin * 2 + rectTitle.height() + popVerctorMargin + rectVlaue.height();


                if (py + popOffset + popHeight > parentHeight) {//往上翻
                    tempOffsetY = -popOffset - popHeight;
                }
                if (px + popOffset + popWidth > parentWidth) {//画到左边
                    tempOffsetX = -popOffset - popWidth;
                }

                tempBitmap = Bitmap.createBitmap(popWidth, popHeight, Bitmap.Config.ARGB_8888);
                tempCanvas = new Canvas(tempBitmap);
                tempCanvas.drawColor(popColor);

                //绘制文字,从右边往坐标绘制,方便右对齐
                paint.setTextAlign(Paint.Align.RIGHT);
                paint.setColor(Color.WHITE);
                paint.setAlpha(178);
                tempCanvas.drawText(foldStr, popHorizontarMargin + maxPopTitleWidth, popTopMargin + rectVlaue.height(), paint);
                tempCanvas.drawText(barStr, popHorizontarMargin + maxPopTitleWidth, popTopMargin + rectVlaue.height() * 2 + popVerctorMargin, paint);

                paint.setTextAlign(Paint.Align.LEFT);
                paint.setAlpha(255);
                tempCanvas.drawText(foldValue, popHorizontarMargin + maxPopTitleWidth + popHorizontarMargin, popTopMargin + rectVlaue.height(), paint);
                tempCanvas.drawText(barValue, popHorizontarMargin + maxPopTitleWidth + popHorizontarMargin, popTopMargin + rectVlaue.height() * 2 + popVerctorMargin, paint);
                changeSelIndex = false;
            }

            //再次优化逻辑,在边界处,允许切换一次浮框位置,由于滑动变化的时水平方向,只会在水平方向上位置变化,垂直方向不用考虑
            if (px + tempOffsetX < 0) {
                tempOffsetX = popOffset;//浮框到右边
            }
            if (px + tempOffsetX + tempBitmap.getWidth() > parentWidth) {
                tempOffsetX = -popOffset - tempBitmap.getWidth();//浮框到左边
            }

            canvas.drawBitmap(tempBitmap, px + tempOffsetX, py + tempOffsetY, paint);
        }

接着处理item被回收后,浮框立即跟着消失的问题

        @Override
        public void onDrawOver(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
            super.onDrawOver(canvas, parent, state);
            Log.i("MChartItemDecoration", "onDrawOver: ");
//            Rect targetRect = new Rect(50, 50, 1000, 200);

            int childCount = parent.getChildCount();
            int preX = 0;
            int preY = 0;
            boolean contantSelIndex = false;
            for (int i = 0; i < childCount; i++) {
                View childAt = parent.getChildAt(i);
                int px = childAt.getLeft() + childAt.getWidth() / 2;
                int py = parent.getHeight();//在RecyclerView的底部绘制,坐标系以RecyclerView的区域为参考
                //绘制X轴坐标
                paint.setColor(xColor);
                drawXValue(canvas, paint, (parent.getChildLayoutPosition(childAt) + 1) + "月", px, py);
                DataEntity dataEntity = dataEntities[parent.getChildLayoutPosition(childAt)];
                py = (int) (maxHeith - dataEntity.foldValue * scale);

                //绘制圆圈
                paint.setColor(ovilColor);
                canvas.drawOval(new RectF(px - radiusOvil, py - radiusOvil, px + radiusOvil, py + radiusOvil), paint);
                if (i > 0) {
                    canvas.drawLine(preX, preY, px, py, paint);
                }
                if (selIndex == parent.getChildLayoutPosition(childAt)) {
                    contantSelIndex = true;
                    //如果被选中,画一条竖线
                    paint.setColor(selColor);
                    canvas.drawLine(px, 0, px, maxHeith, paint);

                    drawPopWin(canvas, px, py, parent.getWidth(), maxHeith, dataEntity);
                }
                //记录当前的圆圈的坐标点,避免画线的时候再计算
                preX = px;
                preY = py;

            }

            if (selIndex!=-1&&!contantSelIndex) {//选中的item被回收了,那就说明内容很多,不考虑,一个item超宽的问题
                if (parent.getChildCount() > 2) {
                    //找两个锚点,计算item直接的距离
                    View childAt0 = parent.getChildAt(0);
                    View childAt1 = parent.getChildAt(1);
                    int step = childAt1.getLeft() - childAt0.getLeft();
                    //确定第一个item的x轴坐标
                    int px0 = childAt0.getLeft() + childAt0.getWidth() / 2;
                    //第一个item在数据集中位置
                    int childLayoutPosition = parent.getChildLayoutPosition(childAt0);
                    //计算选中的item的坐标,x轴位置,通过与childAt0的计算
                    int px = px0 + (selIndex - childLayoutPosition) * step;
                    int py = (int) (maxHeith - dataEntities[selIndex].foldValue * scale);
                    drawPopWin(canvas, px, py, parent.getWidth(), maxHeith, dataEntities[selIndex]);
                }
            }
        }

引入了一个标签,当循环绘制当前item时,若没有检查到selIttem时,说明item被回收,通过视图中的第一个view的位置,与selItem在数据集中的差距来定位selItem在坐标系中的位置,然后绘制浮框。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,602评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,442评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,878评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,306评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,330评论 5 373
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,071评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,382评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,006评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,512评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,965评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,094评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,732评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,283评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,286评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,512评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,536评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,828评论 2 345

推荐阅读更多精彩内容