先上要实现的效果图
整体布局
item的布局,也即柱状图的布局,改变TextView的高度来实现柱状图,外面套一个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 {
@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不用考虑这么多,而且能有很好的复用。
添加选中的竖线
@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 并通知刷新。
接下来看看头疼的选中后的浮框实现。
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);
}
接下来处理边界检测的问题,
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);
}
由于滑动过程中,他会一直检测重绘,这里还有两个问题
- 在靠边的的地方左右滑动,浮框会左右跳跃
- 在往右侧活动的过程中,若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在坐标系中的位置,然后绘制浮框。