Android动态图表

时间:2012-01-16 10:18:33

标签: android dynamic charts real-time

嗨Android开发者,      目前我正在开发一个基于财务的图表应用程序,我在jjoe64博客的帮助下绘制图表。但现在我要实现实时图表。例如,图表在表面中自动绘制,每秒或每分钟一次在服务器端进行更改。任何人都可以实现这类任务。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:11)

好的,我强烈建议使用AChartEngine。它是免费的,轻量级的,并支持许多类型的图表饼图,图表等。为了动态更新图表我通过在单独的线程中添加值来实现这一点。这是我的例子,它没什么特别的:

package my.pack;

import java.util.Date;
import java.util.Random;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;

 public class ChartsActivity extends Activity {

private static Random random = new Random();

private static TimeSeries timeSeries;
private static XYMultipleSeriesDataset dataset;
private static XYMultipleSeriesRenderer renderer;
private static XYSeriesRenderer rendererSeries;
private static GraphicalView view;
private static Thread mThread;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     

    dataset = new XYMultipleSeriesDataset();

    renderer = new XYMultipleSeriesRenderer();
    renderer.setAxesColor(Color.BLUE);
    renderer.setAxisTitleTextSize(16);
    renderer.setChartTitle("Time");
    renderer.setChartTitleTextSize(15);
    renderer.setFitLegend(true);
    renderer.setGridColor(Color.LTGRAY);
    renderer.setPanEnabled(true, true);
    renderer.setPointSize(10);
    renderer.setXTitle("Time");
    renderer.setYTitle("Number");
    renderer.setMargins( new int []{20, 30, 15, 0});
    renderer.setZoomButtonsVisible(true);
    renderer.setBarSpacing(10);
    renderer.setShowGrid(true);


    rendererSeries = new XYSeriesRenderer();
    rendererSeries.setColor(Color.RED);
    renderer.addSeriesRenderer(rendererSeries);
    rendererSeries.setFillPoints(true);
    rendererSeries.setPointStyle(PointStyle.CIRCLE);

    timeSeries = new TimeSeries("Random");
    mThread = new Thread(){
        public void run(){
            while(true){
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
                timeSeries.add(new Date(), random.nextInt(10));
                view.repaint();
            }
        }
    };
    mThread.start();
}

@Override
protected void onStart() {
    super.onStart();
    dataset.addSeries(timeSeries);
    view = ChartFactory.getTimeChartView(this, dataset, renderer, "Test");
    view.refreshDrawableState();
    view.repaint();
    setContentView(view);    
}

}

将自己的值添加到线程中。您可能需要了解如何使用AChartEngine库。 快乐的编码!