Android achartengine 动态展示数据
1.去官网下载achartengine jar包 以及demo 我这用的是achartengine-1.1.0
地址:https://code.google.com/p/achartengine/
主界面MapChartActivity
package com.example.workchart;
import java.util.Timer;
import java.util.TimerTask;
import org.achartengine.GraphicalView;
import com.example.chart.MyLine;
import com.example.chart.PieChart;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
/**
* 管理图表Activity
*
* @author xinnan
*
*/
public class MapChartActivity extends Activity {
private Timer timer = new Timer();
private TimerTask task;
private Handler handler;
private GraphicalView lineChart;
private GraphicalView pieChart;
private Context context;
int[] xv = new int[100];
int[] yv = new int[100];
private Spinner spinnerD;
private Spinner spinnerP;
private static final String[] m = { "A型", "B型", "O型", "AB型", "其他" };
private MyLine mychart;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinnerD = (Spinner) findViewById(R.id.download);
spinnerP = (Spinner) findViewById(R.id.perdevice);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, m);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerD.setAdapter(adapter);
spinnerD.setVisibility(View.VISIBLE);
spinnerP.setAdapter(adapter);
context = getApplicationContext();
// 这里获得main界面上的布局,下面会把图表画在这个布局里面
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
// 添加线型图=============
mychart = new MyLine(context);
lineChart = mychart.getView();
// 将图表添加到布局中去
layout.addView(lineChart, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// 添加饼图=============
pieChart = new PieChart(context).getView();
LinearLayout layout2 = (LinearLayout) findViewById(R.id.linearLayout2);
layout2.addView(pieChart, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// 这里的Handler实例将配合下面的Timer实例,完成定时更新图表的功能
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 刷新图表
mychart.updateCharts();
super.handleMessage(msg);
}
};
task = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
// 每秒刷新一次
timer.schedule(task, 1000, 1000);
}
@Override
public void onDestroy() {
// 当结束程序时关掉Timer
timer.cancel();
super.onDestroy();
}
}
线型图类 MyLine
package com.example.chart;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint.Align;
/**
* 线型图
*
* @author xinnan
*
*/
public class MyLine {
private Context context;
private GraphicalView chart;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer renderer;
private String[] titles = new String[] { "MP4", "Other", "Skype",
"YouTube", "Google Mail" };
public MyLine(Context context) {
this.context = context;
}
public GraphicalView getView() {
// 创建一个数据集的实例,这个数据集将被用来创建图表
mDataset = new XYMultipleSeriesDataset();
// 添加点的集合
List<XYSeries> xySeries = getXYSeries(titles);
for (int i = 0; i < xySeries.size(); i++) {
mDataset.addSeries(xySeries.get(i));
}
// 给节点集合添加样式
renderer = new XYMultipleSeriesRenderer();
// 线条颜色
int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA,
Color.YELLOW, Color.CYAN };
// 线条风格
PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE,
PointStyle.DIAMOND, PointStyle.TRIANGLE, PointStyle.SQUARE,
PointStyle.CIRCLE };
// 添加点的样式
List<XYSeriesRenderer> xyRenderer = getXYSeriesRenderer(colors, styles);
for (int i = 0; i < xyRenderer.size(); i++) {
renderer.addSeriesRenderer(xyRenderer.get(i));
}
// 设置好图表的样式
setChartSettings(renderer, "X", "Y", 0, 100, 0, 90, Color.RED,
Color.BLUE);
System.out.println("一共有" + mDataset.getSeriesCount() + "条点的集合");
System.out.println("一共有" + renderer.getSeriesRendererCount() + "边的样式");
chart = ChartFactory.getLineChartView(context, mDataset, renderer);
return chart;
}
/**
* 构建一组点集合的样式
*
* @param colors
* @param styles
* @return
*/
private List<XYSeriesRenderer> getXYSeriesRenderer(int[] colors,
PointStyle[] styles) {
List<XYSeriesRenderer> list = new ArrayList<XYSeriesRenderer>();
for (int i = 0; i < colors.length; i++) {
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(colors[i]);
r.setPointStyle(styles[i]);
r.setFillPoints(true);
r.setLineWidth(3);
list.add(r);
}
return list;
}
/**
* 构建一组空的点集合
*
* @param titles
* 标题数组
* @return
*/
private List<XYSeries> getXYSeries(String[] titles) {
List<XYSeries> list = new ArrayList<XYSeries>();
for (int i = 0; i < titles.length; i++) {
// 这个类用来放置曲线上的所有点,是一个点的集合,根据这些点画出曲线
XYSeries series = new XYSeries(titles[i]);
list.add(series);
}
return list;
}
/**
* 设置线型图属性
*
* @param renderer
* @param xTitle
* @param yTitle
* @param xMin
* @param xMax
* @param yMin
* @param yMax
* @param axesColor
* @param labelsColor
*/
protected void setChartSettings(XYMultipleSeriesRenderer renderer,
String xTitle, String yTitle, double xMin, double xMax,
double yMin, double yMax, int axesColor, int labelsColor) {
// 有关对图表的渲染可参看api文档
renderer.setChartTitle("abc");
renderer.setBackgroundColor(Color.WHITE);
renderer.setXTitle(xTitle);
renderer.setYTitle(yTitle);
renderer.setXAxisMin(xMin);
renderer.setXAxisMax(xMax);
renderer.setYAxisMin(yMin);
renderer.setYAxisMax(yMax);
renderer.setAxesColor(axesColor);// 设置轴线颜色
renderer.setLabelsColor(labelsColor);// 设置上左右Label颜色
renderer.setShowGrid(true);// 是否显示网格
renderer.setXLabels(20);
renderer.setYLabels(10);
renderer.setXTitle("Time");
renderer.setYTitle("dBm");
renderer.setYLabelsAlign(Align.RIGHT);
renderer.setPointSize((float) 2);
renderer.setShowLegend(false);
renderer.setPanLimits(new double[] { -10, 120, -10, 100 });// 设置可拖动范围
renderer.setMarginsColor(Color.WHITE);// 线型图外边框背景颜色
renderer.setXLabelsColor(Color.BLUE);// 横坐标字体显示的颜色
renderer.setYLabelsColor(0, Color.BLUE);// 纵坐标字体显示颜色
// 设置背景颜色
renderer.setApplyBackgroundColor(true);
renderer.setBackgroundColor(Color.WHITE);// 线型图背景颜色
}
/**
* 动态改变数据
*/
public void updateCharts() {
// * 1.删除数据集中的点集合
// * 2.限制点显示的范围
// * 3.将旧的点集中x和y的数值取出来放入backup中,并且将x的值加1,造成曲线向右平移的效果
// * 4.将新产生的点首先加入到点集中,然后在循环体中将坐标变换后的一系列点都重新加入到点集中
// * 5.给数据集重新添加新的点集合
// * 6.视图更新
// 设置好下一个需要增加的节点
int x = 100;
int[] tempX = new int[100];
int[] tempY = new int[100];
XYSeries[] series = mDataset.getSeries();
int seriesSize = series.length;
for (int i = 0; i < seriesSize; i++) {
mDataset.removeSeries(series[i]);
}
for (int i = 0; i < seriesSize; i++) {
// 判断当前点集中到底有多少点,因为屏幕总共只能容纳100个,所以当点数超过100时,长度永远是100
int xyCount = series[i].getItemCount();
if (xyCount > 100) {
xyCount = 100;
}
// 得到series 里面的数据,保存到临时变量中,然后再删除series中的数据
for (int j = 0; j < xyCount; j++) {
// 将旧的点集中x和y的数值取出来放入backup中,并且将x的值加1,造成曲线向右平移的效果
tempX[j] = (int) series[i].getX(j) - 1;
tempY[j] = (int) series[i].getY(j);
}
// 点集先清空,为了做成新的点集而准备
series[i].clear();
// 保存一个新的点 这儿可进行判断series 是哪条线
String title = series[i].getTitle();
if (title.equals(titles[0])) {
series[i].add(x, (int) (Math.random() * 10));
} else if (title.equals(titles[1])) {
series[i].add(x, (int) (10 + Math.random() * 20));
} else if (title.equals(titles[2])) {
series[i].add(x, (int) (20 + Math.random() * 30));
} else if (title.equals(titles[3])) {
series[i].add(x, (int) (30 + Math.random() * 40));
} else if (title.equals(titles[4])) {
series[i].add(x, (int) (40 + Math.random() * 50));
}
// 把旧的点集合再添加进去
for (int j = 0; j < xyCount; j++) {
series[i].add(tempX[j], tempY[j]);
}
mDataset.addSeries(series[i]);
}
// 视图更新,没有这一步,曲线不会呈现动态
// 如果在非UI主线程中,需要调用postInvalidate(),具体参考api
chart.invalidate();
}
}
饼图类 PieChart
注意饼图类继承了achartengine demo 中的AbstractDemoChart 实现了IDemoChart接口
package com.example.chart;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import android.content.Context;
import android.graphics.Color;
/**
* 饼图
*
* @author xinnan
*
*/
public class PieChart extends AbstractDemoChart {
private Context context;
public PieChart(Context context) {
this.context = context;
}
@Override
public String getName() {
return null;
}
@Override
public String getDesc() {
return null;
}
/**
* 得到饼图
*/
@Override
public GraphicalView getView() {
double[] values = new double[] { 12, 14, 11, 10, 19 };
int[] colors = new int[] { Color.BLUE, Color.GREEN, Color.MAGENTA,
Color.YELLOW, Color.CYAN };
// 构建饼图数据
CategorySeries dataset = buildCategoryDataset("abc", values);
// 渲染饼图(填充颜色)
DefaultRenderer renderer = buildCategoryRenderer(colors);
// 设置饼图文字字体大小和饼图标签字体大小
renderer.setLabelsTextSize(15);
renderer.setLegendTextSize(15);
// 消除锯齿
renderer.setAntialiasing(true);
// 设置背景颜色
renderer.setApplyBackgroundColor(true);
renderer.setBackgroundColor(Color.WHITE);
// 设置线条颜色
renderer.setAxesColor(Color.WHITE);
GraphicalView pieView = ChartFactory.getPieChartView(context, dataset,
renderer);
return pieView;
}
}