1. 程式人生 > >Android MPAndroidCharts 框架 畫可滑動檢視的直方圖

Android MPAndroidCharts 框架 畫可滑動檢視的直方圖

1.因為公司專案的需求,所以花了1.2天研究 MPAndroidCharts框架 。但是發現好多部落格對我都沒得幫助,浪費很多時間在百度上,不得不說google 真是比百度強太多了。

要求:統計出56個名族的數量

2.用到的框架是MPAndroidCharts。引入的依賴:

compile 'com.github.PhilJay:MPAndroidChart:v3.0.2' 
然後在引入倉庫


3.正式開始使用

xml檔案:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="aas.androidmpcharts.MainActivity">

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/mBarChart"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        />
</RelativeLayout>
MainActivity程式碼:
public class MainActivity extends AppCompatActivity {
    BarChart mBarChart;
    ArrayList<String> mlist=new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBarChart = (BarChart) findViewById(R.id.mBarChart);

        mBarChart.setDrawBarShadow(false);     //表不要陰影
        mBarChart.setDrawValueAboveBar(true);
        Description description=new Description();
        description.setText("通行民族");
        mBarChart.setDescription(description);  //表的描述資訊

        mBarChart.setPinchZoom(false);
        mBarChart.setMaxVisibleValueCount(60); //最大顯示的個數。超過60個將不再顯示
        mBarChart.setScaleEnabled(false);     //禁止縮放
        mBarChart.setDragEnabled(true);// 是否可以拖拽
        mBarChart.setHighlightPerDragEnabled(true);// 拖拽超過圖示繪製畫布時高亮顯示
        mBarChart.setDrawGridBackground(false);//
      /*  mBarChart.setAutoScaleMinMaxEnabled(true);*/
       /* mBarChart.animateX(500);//資料顯示動畫,從左往右依次顯示*/
       /* mBarChart.getAxisRight().setEnabled(false);*/
        /*mBarChart.setDragDecelerationEnabled(true);*///拖拽滾動時,手放開是否會持續滾動,預設是true(false是拖到哪是哪,true拖拽之後還會有緩衝)
        mBarChart.zoom(2.5f,1f,0,0);//顯示的時候 是 按照多大的比率縮放顯示   1f表示不放大縮小
        //我預設手機螢幕上顯示10  剩下的滑動直方圖 然後顯示。。假如要顯示25個 那麼除以10 就是放大2.5f。。同理
        // 56個民族   那麼放大5.6f

        draw();
    }

    public void draw(){

        //X軸 樣式
        final XAxis xAxis = mBarChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelRotationAngle(90);//柱的下面描述文字  旋轉90度
        xAxis.setDrawLabels(true);
        xAxis.setDrawGridLines(false);
        xAxis.setTypeface(Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"));//字型的相關的設定
        xAxis.setGranularity(1f);//設定最小間隔,防止當放大時,出現重複標籤。
        xAxis.setCenterAxisLabels(true);//字型下面的標籤 顯示在每個直方圖的中間
        xAxis.setLabelCount(11,true);//一個介面顯示10個Lable。那麼這裡要設定11個
        xAxis.setTextSize(10f);


        //Y軸樣式
        YAxis leftAxis = mBarChart.getAxisLeft();
        leftAxis.setLabelCount(10);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setStartAtZero(false);
        leftAxis.setYOffset(10f);


        //這個替換setStartAtZero(true)
        leftAxis.setAxisMaxValue(50f);
        leftAxis.setAxisMinValue(0f);
        leftAxis.setDrawGridLines(true);//背景線
        leftAxis.setAxisLineColor(getResources().getColor(R.color.colorPrimaryDark));




        //.設定比例圖示的顯示隱藏
        Legend l = mBarChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        //樣式
        l.setForm(Legend.LegendForm.CIRCLE);
        //字型
        l.setFormSize(10f);
        //大小
        l.setTextSize(13f);
        l.setFormToTextSpace(10f);
        l.setXEntrySpace(10f);



        //模擬資料
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        yVals1.add(new BarEntry(1,23));
        yVals1.add(new BarEntry(2, 20));
        yVals1.add(new BarEntry(3, 30));
        yVals1.add(new BarEntry(4, 10));
        yVals1.add(new BarEntry(5, 45));
        yVals1.add(new BarEntry(6, 50));
        yVals1.add(new BarEntry(7, 35));
        yVals1.add(new BarEntry(8, 26));
        yVals1.add(new BarEntry(9, 14));
        yVals1.add(new BarEntry(10, 20));
        yVals1.add(new BarEntry(11, 33));
        yVals1.add(new BarEntry(12, 44));
        yVals1.add(new BarEntry(13, 42));
        yVals1.add(new BarEntry(14, 41));
        yVals1.add(new BarEntry(15, 12));
        yVals1.add(new BarEntry(16, 31));
        yVals1.add(new BarEntry(17, 21));
        yVals1.add(new BarEntry(18, 20));
        yVals1.add(new BarEntry(19, 44));
        yVals1.add(new BarEntry(20, 42));
        yVals1.add(new BarEntry(21, 41));
        yVals1.add(new BarEntry(22, 12));
        yVals1.add(new BarEntry(23, 31));
        yVals1.add(new BarEntry(24, 21));
        yVals1.add(new BarEntry(25, 20));
        setData(yVals1);
    }
    private void setData(ArrayList yVals1) {
        for(int i=1;i<=yVals1.size();i++) {
            mlist.add(""+i);
        }
        IAxisValueFormatter ix=new MyXAxisValueFormatter(mlist);
        mBarChart.getXAxis().setValueFormatter(ix);

        BarDataSet set1;
        if (mBarChart.getData() != null &&
                mBarChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mBarChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mBarChart.getData().notifyDataChanged();
            mBarChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "The year 2017");
            set1.setColors(ColorTemplate.MATERIAL_COLORS);
            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);
            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(1f);
            mBarChart.setData(data);
        }
    }

    public class MyXAxisValueFormatter implements IAxisValueFormatter {

        private List<String> mValues;

        public MyXAxisValueFormatter(List<String> values) {
            this.mValues = values;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
           int x=(int)(value);
            if (x<0)
                x=0;
            if (x>=mValues.size())
                x=mValues.size()-1;
            return mValues.get(x);
        }
    }
}

最後的結果:


在做的過程中遇到的幾個坑說下::

1.xAxis.setAxisMaximum(500f); 設定x軸的最大軸。最開始我是這樣設定的。。然後新增BarEntry的時候,隨便填寫x軸的座標。但是最後發現有bug

媽的。 糾結了很久。 然後看原作者的demo ,發現作者並沒有呼叫xAxis.setAxisMaximum(500f)。。每個直方圖的座標從1,開始往後數。記住一定要從1
開始。。從0開始會遇到問題。
2.如何給 每個直方圖 下面新增標籤:主要用到的是IAxisValueFormatter 重寫
public String getFormattedValue(float value, AxisBase axis)通過這個value值 獲取標籤。。但是我debug發現 這個value並不是嚴格的1
,2,3,4,5 等等 這樣按照順序遍歷的。所以這個方法 我不是很理解。看作者的程式碼也看不懂。坑