轉載請注明:http://blog.csdn.net/ly20116/article/details/50905789
MPAndroidChart是一個非常優秀的開源圖表庫,MPAndroidChart可以繪制各種常用的圖表類型:折線圖、柱形圖、餅圖、散點圖等等。
github地址:https://github.com/PhilJay/MPAndroidChart
具體的導入方式就不再詳細的說了,本文主要解決在圖例后面加上數字或文本或占的百分比等,也就是定制想要的圖例。
MPAndroidChart的提供的餅圖圖例是這種: (注:圖片為引用)

而我們想要實現的效果是這種: 
就是在圖例后面加上數字或文本
通過借鑒Stackoverflow上的大神的解決方案:
https://stackoverflow.com/questions/29139061/mpandroidchart-legend-customization
下面來開始我們的項目:
一、獲取Legend,使Legend不顯示
Legend legend=mPieChart.getLegend();//設置比例圖 legend.setEnabled(false);//圖例不顯示
- 1
- 2
二、定義數組colors和labels及數據datas
private int[] colors;//顏色集合 private String[] labels;//標簽文本 private float[] datas={16912f,2488f,600f};//數據,可以是任何類型的數據,如String,int
- 1
- 2
- 3
三、獲取Legend中的colors和labels
colors=legend.getColors(); labels=legend.getLabels();
- 1
- 2
四、定義customizeLegend()方法,實現圖例的繪制
/** * 定制圖例,通過代碼生成布局 */ private void customizeLegend(){ for(int i=0;i<datas.length;i++){ LinearLayout.LayoutParams lp=new LinearLayout. LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); lp.weight=1;//設置比重為1 LinearLayout layout=new LinearLayout(this);//單個圖例的布局 layout.setOrientation(LinearLayout.HORIZONTAL);//水平排列 layout.setGravity(Gravity.CENTER_VERTICAL);//垂直居中 layout.setLayoutParams(lp); //添加color LinearLayout.LayoutParams colorLP=new LinearLayout. LayoutParams(20,20); colorLP.setMargins(0, 0, 20, 0); LinearLayout colorLayout=new LinearLayout(this); colorLayout.setLayoutParams(colorLP); colorLayout.setBackgroundColor(colors[i]); layout.addView(colorLayout); //添加label TextView labelTV=new TextView(this); labelTV.setText(labels[i]+" "); layout.addView(labelTV); //添加data TextView dataTV=new TextView(this); dataTV.setText(datas[i]+""); layout.addView(dataTV); legendLayout.addView(layout);//legendLayout為外層布局即整個圖例布局,是在xml文件中定義 } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
圖例示意圖: 
customizeLegend()方法的調用可在設置圖例不顯示的后面,也可以在其它地方調用,但是必須在PieChart調用setData()方法的后面,這樣才能獲取到colors和labels.
總結:
簡而言之,就是獲取legend的顏色colors和標簽文本labels,然后結合自己的數據,在新的布局中繪制即可。
你可以在圖例后面添加更多的類型的數據。
圖例布局的位置可以在xml文件中設置。
也可以實現各種布局的圖例。
