最近做的項(xiàng)目里用到了圖表控件MPAndroidChart,看了github的英文文檔竖独,干脆把它翻譯出來裤唠。
一、準(zhǔn)備開始
本章涵蓋了使用這個(gè)庫的基本設(shè)置莹痢。
添加依賴關(guān)系
添加這個(gè)庫的依賴到你的項(xiàng)目种蘸。如何操作已經(jīng)在repository的usage里寫明墓赴。推薦使用Gradle來添加這個(gè)庫的依賴。
創(chuàng)建View
在xml中定義LineChart,BarChart,ScatterChart,CandleStickChart,PieChart, BubbleChart or RadarChart:
<com.github.mikephil.charting.charts.LineChart
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="match_parent" />
然后從你的Activity劈彪、Fragment或者其他什么中取到她:
// in this example, a LineChart is initialized from xml
LineChart chart = (LineChart) findViewById(R.id.chart);
或者創(chuàng)建它在代碼中(然后增加它到一個(gè)布局中):
// programmatically create a LineChart
LineChart chart = new LineChart(Context);
// get a layout defined in xml
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
rl.add(chart); // add the programmatically created chart
添加數(shù)據(jù)
在獲得圖表的實(shí)例后,你就可以創(chuàng)建數(shù)據(jù)并將其添加到圖表當(dāng)中竣蹦。下面的例子使用了LineChart,包含x和y坐標(biāo)的Entry類是圖表的單一入口沧奴。其他圖表類型,如柱形圖表使用其他類(例如BarEntry)痘括。
將數(shù)據(jù)添加到你的圖表,需要把每個(gè)數(shù)據(jù)對象包裝成一個(gè)Entry對象,就像下面這樣子:
YourData[] dataObjects = ...;
List<Entry> entries = new ArrayList<Entry>();
for (YourData data : dataObjects) {
// turn your data into Entry objects
entries.add(new Entry(data.getValueX(), data.getValueY()));
}
下一步,你需要將你創(chuàng)建的List<Entry> 添加到LineDataSet對象中滔吠。DataSet對象保存數(shù)據(jù)并允許個(gè)人風(fēng)格的數(shù)據(jù)纲菌。如果enabled,下面用“標(biāo)簽”只有一個(gè)描述性的目的并且出現(xiàn)在圖例(Legend)中疮绷。
LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset
dataSet.setColor(...);
dataSet.setValueTextColor(...); // styling, ...
最后一步,你需要將你創(chuàng)建的LineDataSet對象添加LineData對象中翰舌。這個(gè)對象持有所有數(shù)據(jù),這些數(shù)據(jù)在圖標(biāo)中被顯示出來,并且允許更進(jìn)一步的樣式定制。創(chuàng)建數(shù)據(jù)對象后,你可以將它設(shè)置到圖表中冬骚,然后刷新:
LineData lineData=new LineData(dataSet);
chart.setData(lineData);
chart.invalidate(); // refresh
請認(rèn)真思考上述場景的基本設(shè)置椅贱。更詳細(xì)解釋請參閱setting data部分,這也解釋了如何將數(shù)據(jù)添加到各種基于例子的圖表類型。
樣式
想了解更多關(guān)于圖表和數(shù)據(jù)的settings & styling,請?jiān)L問general settings & styling部分只冻。關(guān)于更具體的樣式和設(shè)置的圖表類型,請看看 specific settings & styling wiki頁面庇麦。