前面我们对Flotr2进行了简要的介绍,也对它的API进行了一些说明.Flotr2对手机平台支持良好.在Android中,我们可以结合WebView使用Flotr2绘制图表.

下面新建一个Flotr2Demo来演示Flotr2的使用.

flotr2.min.js拷贝到项目的assets目录下,新建chart.html:

Flotr2Demo_1
Flotr2Demo_1

 <!DOCTYPE html>
 <html>
   <head>

     <style type="text/css">
      body {
        margin:  0px;
        padding: 0px;
      }
      #container {
        width : 280px;
        height: 225px;
        margin: 0px auto;
      }
     </style>

   </head>
   <body>
     <div id="container">  </div>
     <script type="text/javascript" src="flotr2.min.js">  </script>
     <script type="text/javascript">
    function drawChart(data,option){
       var container = document.getElementById("container");
       Flotr.draw(container, data, option);
      }
     </script>
   </body>
 </html>

我们在chart.html中定义了一个drawChart(data,option)方法,通过传入的数据和Flotr2的配置绘制图表.所以我们还需要新建一个Activity并添加一个WebView组件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ChartActivity"
    android:gravity="center" >

     <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       />

 </RelativeLayout>

然后在Activity中初始化WebView,并启用JavaScript支持:

@SuppressLint("SetJavaScriptEnabled")
	private void initViews() {
		webView = (WebView) findViewById(R.id.webView);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebChromeClient(new WebChromeClient());
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				webView.loadUrl("javascript:drawChart(["+data+"],"+option+")");
			}

		});

		webView.loadUrl("file:///android_asset/chart.html");
	}

其中的data和option根据我们传入的图表类型进行设置:

private void initChartData(String type) {
		if ("lines".equals(type)) {
			data = "[[0, 3], [4, 8], [8, 5], [9, 13]]";
			option = "{ xaxis: { minorTickFreq: 4}, grid: {minorVerticalLines: true}}";
		}else if ("bars".equals(type)) {
			String bj = " [[1, -9], [2, 1], [3, 12], [4, 20],[5, 26], [6, 30], [7, 32], [8, 29],[9, 22], [10, 12], [11, 0], [12, -6]]";
			data = "{ data : "+bj+", label :'北京' ,bars : { show : true }}";

			//我们也可以不设置option,当option为空时,将使用flotr2的默认配置
		}else if ("pie".equals(type)) {
			data = " { data : [[0, 4]], label : 'Comedy' }, { data :[[0, 3]], label : 'Action' },{ data : [[0, 1.03]], label : 'Romance',pie : {explode : 50} }, { data : [[0, 3.5]], label : 'Drama' }";
			option = "{mouse : { track : true },pie : {show : true, explode : 6}}";
		}else if ("points".equals(type)) {
			String sz = "[[1, 15], [2, 16], [3, 19], [4, 22],[5, 26], [6, 27], [7, 28], [8, 28],[9, 27], [10, 25], [11, 20], [12, 16]]";
		    data = " { data : "+sz+", label :'深圳' , points : { show : true }}";

		}else if ("radar".equals(type)) {
			String s1 ="{ label : 'Actual', data : [[0, 3], [1, 8], [2, 5], [3, 5], [4, 3], [5, 9]] }";
			String s2 = "{ label : 'Target', data : [[0, 8], [1, 7], [2, 8], [3, 2], [4, 4], [5, 7]] }";
			// Radar Labels
			String ticks = "[[0, 'Statutory'],[1, 'External'], [2, 'Videos'],[3, 'Yippy'],[4, 'Management'],[5, 'oops']]";

			data = s1+","+s2;
			option = "{radar : { show : true}, grid  : { circular : true, minorHorizontalLines : true}, yaxis : { min : 0, max : 10, minorTickFreq : 2}, xaxis : { ticks : "+ticks+"}}";

		}else if ("bubble".equals(type)) {

			String [] d1 = new String[10];
			String [] d2 = new String[10];

			for(int i=0;i <10;i++){
				d1[i] = "["+i+","+Math.ceil(Math.random()*10)+","+Math.ceil(Math.random()*10)+"]";
				d2[i] = "["+i+","+Math.ceil(Math.random()*10)+","+Math.ceil(Math.random()*10)+"]";
			}

			String str1="[";
			String str2 = "[";

			for(String str:d1){
				str1+=str+",";
			}
			for(String str:d2){
				str2+= str+",";
			}
			data = str1.substring(0, str1.length()-1)+"],\n"+str2.substring(0, str2.length()-1)+"]";

			option = "{ bubbles : { show : true, baseRadius : 5 },xaxis   : { min : -4, max : 14 },yaxis   : { min : -4, max : 14 }}";
		}

	}

在Activity的onCreate()方法中先初始化界面并获取MainActivity中传入的要显示的图表类型type:

protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chart);
		initViews();
		type = getIntent().getStringExtra("type");
		initChartData(type);
	}

MainActivity的完整代码如下 :

public class MainActivity extends ListActivity {

	private String[] charts={"折线图","柱状图","饼状图","点状图","雷达图","气泡图"};
	private String[] types = {"lines","bars","pie","points","radar","bubble"};
	private Context ctx;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ctx = this;
		ArrayAdapter <String>  adapter = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1,charts);

		ListView listView= getListView();
		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView <?>  parent, View view,
					int position, long id) {

				Intent intent = new Intent(ctx, ChartActivity.class);
				intent.putExtra("type", types[position]);
				startActivity(intent);

			}
		});
	}

项目运行截图:

Flotr2Demo_2
Flotr2Demo_2

Flotr2Demo_3
Flotr2Demo_3

Flotr2Demo_4
Flotr2Demo_4

Flotr2Demo_5
Flotr2Demo_5

Flotr2Demo_6
Flotr2Demo_6

Flotr2Demo_7
Flotr2Demo_7

Flotr2Demo_8
Flotr2Demo_8

源码下载:https://github.com/liuzc/Flotr2Demo_Android