效果图
核心代码:
1 设置点集
<span style="font-size:18px;"> //设置点集
private XYMultipleSeriesDataset getDataset() {
mDataset = new XYMultipleSeriesDataset();
series = new XYSeries("柱状图");
mDataset.addSeries(series);
return mDataset;
}</span>
2 设置描绘器
<span style="font-size:18px;">private XYMultipleSeriesRenderer getRender() {
mRender = new XYMultipleSeriesRenderer();
setRenderer(mRender, color);
setChartSettings(mRender, title, xMessage, yMessage, yMin, yMax);
mRender.setXLabels(0);//取消X轴数据,自定义显示
mRender.setYLabels(10);//Y轴10等分
mRender.setClickEnabled(true);//不允许点击事件
mRender.setPanEnabled(false, false);//不允许移动
mRender.setShowGrid(true);//显示表格
mRender.setBarSpacing(0.5f);//设置表格的宽度,柱子的宽度也会有所变化
return mRender;
}</span>
3 构建图表
mChartView = ChartFactory.getBarChartView(context, getDataset(),
getRender(), BarChart.Type.DEFAULT);
4 计时器定时刷新
private void sendMessage() {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
updateChart();
}
super.handleMessage(msg);
}
};
task = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
timer.schedule(task, 0, 1000);
}
5 刷新
private void updateChart() {
//随机数模拟数据
int data = (int) (Math.random() * 100);
//x轴显示当前时间(仅仅显示分,秒)
String xDate = nowTime.format(new java.util.Date());
//得到x轴上柱子的数量
int lenght = series.getItemCount();
//此处显示柱子显示的最大数量
if (lenght > xLengh) {
lenght = xLengh;
}
//移除点集
mDataset.removeSeries(series);
//x轴当前点数小于最大点数则直接添加,否则先移除旧点,再添加新点,并转换坐标实现移动效果
if (lenght < xLengh) {
series.add(lenght + 1, data);
mRender.addXTextLabel(lenght + 1, xDate);
xKedu[lenght] = xDate;
} else {
for (int i = 0; i < lenght - 1; i++) {
catchs[i] = (float) (series.getY(i + 1));
xKedu[i] = xKedu[i + 1];
}
series.clear();
for (int i = 0; i < lenght - 1; i++) {
series.add(i + 1, catchs[i]);
mRender.addXTextLabel(i + 1, xKedu[i]);
}
xKedu[xLengh - 1] = xDate;
series.add(xLengh, data);
mRender.addXTextLabel(xLengh, xDate);
}
mDataset.addSeries(series);
//这里实现图表的移动效果
mChartView.invalidate();
}
源码地址:
http://download.csdn.net/detail/huiling815/9653478