最近项目中很多地方使用了图表,使用的图表框架是MPAndroidChart, 由我负责来做。
过程中也花了很多时间了解框架的API,走了挺多的弯路,记录下一些效果的实现:
Chart常用设置
chart的常用设置以及坐标轴配置。
1 | mChart.setDrawValueAboveBar(false); |
XAxis,YAxis常用设置
1 | leftAxis.enableGridDashedLine(2f, 2f, 0f); // 画水平虚线 |
强制展示XAxis上面的所有标签
默认是柱状图过密时,Label值会间隔展示,放大才会展示完全(这样实际挺人性化),但是项目需求时展示所有标签.
下面两个设置可以强制展示所有标签:
1 | xAxis.setDrawLabels(true); |
点击高亮标识
1 | LineDataSet set; |
自定义MarkerView
项目需求是:在柱状图根据leftYAxis单位展示markerview, 折线根据rightYAxis的单位展示markerview.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31public class XXMarkerView extends MarkerView {
private TextView tvContent;
private RelativeLayout layout;
public XXMarkerView(Context context, int layoutResource) {
super(context, layoutResource);
layout = (RelativeLayout) findViewById(R.id.tvRelativeLayout);
tvContent = (TextView) findViewById(R.id.tvContent);
}
public void refreshContent(Entry e, Highlight highlight) {
float yValues = e.getY();
if (e instanceof BarEntry) {
tvContent.setText(yValues);
} else if(e instanceof PieEntry) { // 饼图
// set the entry-value as the display text
} else {
// 这里展示直线单位,如果还有其它类型的Entry,继续写在上面else if()中
// 折线数据源是Entry,public LineDataSet(List<Entry> yVals, String label)
tvContent.setText(yValues + "%");
}
}
public int getXOffset(float xpos) {
return -(getWidth() / 2);
}
public int getYOffset(float ypos) {
return -getHeight() - 20;
}
使用方式:1
2XXMarkerView mv = new XXMarkerView (context, R.layout.marker_view);
mChart.setMarkerView(mv);
自定义Legend
Legend使用官方说明:https://github.com/PhilJay/MPAndroidChart/wiki/Legend
mChart.getLegend() 自带的产生的legend有局限,在Legend setPosition()设置BELOW_CHART_CENTER时,刷新图表高度会发生变化,有时候legend甚至不展示。
网上有的在说这是一个bug。
换一种解决办法:
可以隐藏Legend( mChart.getLegend().setEnabled(false);
),自己定义一个布局,设置为Chart的Legend。
很好地解决了我的问题,因为我的legend中不仅有纯色块,还有图片。
1 | private static void setCustomLegend(LinearLayout llCustomLegend, Legend l, Context context) { |
想用图片时,改动一下实用Drawable即可。
ref: 1. [pandroidchart-legend-customization][1]
[1]: http://stackoverflow.com/questions/29139061/mpandroidchart-legend-customization/29145904#29145904