Android 系列 5.8使用AndroidPlot显示图表和图表

来源:互联网 发布:淘宝66大促报名入口 编辑:程序博客网 时间:2024/05/16 03:21
5.8使用AndroidPlot显示图表和图表

问题
您希望在Android应用程序中以图形方式显示数据。

使用适用于Android的许多第三方图形库之一。在这个例子中,我们将使用AndroidPlot(一个开源库)来描述一个简单的图形。
讨论
如果您还没有,请从http://androidplot.com/wiki/Download(任何版本)下载AndroidPlot库。
接下来,您需要创建一个新的Android项目,并将AndroidPlot库添加到新项目。为此,请在项目文件夹中创建一个新文件夹,并将其命名为lib。
到这个文件夹添加下载的AndroidPlot JAR文件;它应该被命名为Androidplot-core-0.4a-release.jar或类似的东西。 (在这个阶段,你应该有目录,如src,res,gen和lib。)
要使用库,必须将其添加到构建路径。在Eclipse中,右键单击您添加的.jar文件,然后选择构建路径 - 添加到构建路径选项。这将在Eclipse项目中显示另一个名为Referenced Libraries的目录。
在我们的示例应用程序中,我们对一些数据进行硬编码,并显示与应用程序中的数据相对应的图。因此,我们需要在我们的XML布局(main.xml)中添加一个(x,y)图。示例5-17显示了在线性布局中使用XYPlot组件的main.xml。
实例5-17。使用XYPlot的XML布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><com.androidplot.xy.XYPlotandroid:id="@+id/mySimpleXYPlot"android:layout_width="fill_parent"android:layout_height="wrap_content"title="Stats"/></LinearLayout>

获取对XML中定义的XYPlot的引用:
mySimpleXYPlot =(XYPlot)findViewById(R.id.mySimpleXYPlot);
初始化两个将显示绘图的数字数组:
// Create two arrays of y-values to plot:Number[] series1Numbers = {1, 8, 5, 2, 7, 4};Number[] series2Numbers = {4, 6, 3, 8, 2, 10};

将阵列转换为XY系列:

XYSeries series1 = new SimpleXYSeries(// SimpleXYSeries takes a List so turn our array into a ListArrays.asList(series1Numbers),// Y_VALS_ONLY means use the element index as the x valueSimpleXYSeries.ArrayFormat.Y_VALS_ONLY,// Set the display title of the series"Series1");


创建用于使用LineAndPointRenderer绘制系列的格式化程序:
LineAndPointFormatter series1Format = new LineAndPointFormatter(Color.rgb(0, 200, 0), // line colorColor.rgb(0, 100, 0), // point colorColor.rgb(150, 190, 150)); // fill color (optional)

将series1和series2添加到XY图:
mySimpleXYPlot.addSeries(series1, series1Format);mySimpleXYPlot.addSeries(series2, new LineAndPointFormatter(Color.rgb(0, 0, 200),Color.rgb(0, 0, 100), Color.rgb(150, 150, 190)));

使它看起来更清洁:
// Reduce the number of range labelsmySimpleXYPlot.setTicksPerRangeLabel(3);// By default, AndroidPlot displays developer guides to aid in laying out// your plot. To get rid of them call disableAllMarkup():mySimpleXYPlot.disableAllMarkup();mySimpleXYPlot.getBackgroundPaint().setAlpha(0);mySimpleXYPlot.getGraphWidget().getBackgroundPaint().setAlpha(0);mySimpleXYPlot.getGraphWidget().getGridBackgroundPaint().setAlpha(0);

运行应用程序!它应该如图5-4所示。


图5-4。 AndroidPlot显示
0 0
原创粉丝点击