android绘画折线图二
紧接着android绘画折线图一,下面来介绍第二种方法,使用该方法,首先需要一个Androidplot-core-0.4.3-release.jar,该jar包之后也包含在项目源码中
建立一个android项目:
import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import com.androidplot.xy.SimpleXYSeries; import com.androidplot.series.XYSeries; import com.androidplot.xy.*; import java.util.Arrays; public class SimpleXYPlot extends Activity { private XYPlot mySimpleXYPlot; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Initialize our XYPlot reference: 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}; // Turn the above arrays into XYSeries: XYSeries series1 = new SimpleXYSeries( Arrays.asList(series1Numbers), // SimpleXYSeries takes a List so turn our array into a List SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // Y_VALS_ONLY means use the element index as the x value "Series1"); // Set the display title of the series //SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED; // Same as above, for series2 XYSeries series2 = new SimpleXYSeries(Arrays.asList(series2Numbers), SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, "Series2"); // Create a formatter to use for drawing a series using LineAndPointRenderer: LineAndPointFormatter series1Format = new LineAndPointFormatter( Color.rgb(0, 200, 0), // line color Color.rgb(0, 100, 0), // point color null); // fill color (optional) // Add series1 to the xyplot: mySimpleXYPlot.addSeries(series1, series1Format); // Same as above, with series2: 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 labels mySimpleXYPlot.setTicksPerRangeLabel(3); mySimpleXYPlot.setTicksPerDomainLabel(1); // By default, AndroidPlot displays developer guides to aid in laying out your plot. // To get rid of them call disableAllMarkup(): mySimpleXYPlot.disableAllMarkup(); } }
这种方法需要用到布局文件,接下来看一下main.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.XYPlot android:id="@+id/mySimpleXYPlot" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginTop="10px" android:layout_marginLeft="10px" android:layout_marginRight="10px" title="A Simple XYPlot Example"/> </LinearLayout>
然后运行项目,就出来了一个折线图的效果了
注明:项目源码SimpleXYPlot.zip,Androidplot-core-0.4.3-release.jar包含在其中
成功根本没有什么秘诀可言,如果真是有的话,就是两个:第一个就是坚持到底,永不放弃;第二个是当你想放弃的时候,回过头来看看第一个秘诀:坚持到底,永不放弃