该库github地址:https://github.com/PhilJay/MPAndroidChart
android开发中经常会用到图表类的控件,MPAndroidChart可以很好的实现,不过其api很多,记不住,每次都会开始查,在这里特此总结,做个人笔记使用。
首先该库支持LineChart(折线图)、BarChart(柱状图)、PieChart(饼状图)、ScatterChart(散点图)、CandleStickChart (for financial data)、BubbleChart (area covered by bubbles indicates the yValue)、RadarChart (雷达图)
使用其中控件确实需要比较多的配置,对于刚开始使用的开发者可能比较蒙。
总的来说,第一步:配置该chart这里一般配置背景,图例说明(Legend),X、Y轴等
第二步:数据配置,这里的配置比较多
①配置图表中的数据,该数据采用ArrayList类型的数据存 储,Entry是该库的一个数据类,构造函数Entry(float x,float y)有的版本是Entry(float y,int x),这里的y就是要显示y轴的数据,x并不是x轴显示的数据,这里需要配置(版本不同配置可能也不同)。同时此处是也是配置该数据的具体显示情况。像折线的颜色,数据点的大小等

下面是一个LineChart使用的例子

public class LineChartActivity extends Activity implements View.OnClickListener{

    LineChart mLineChart;
  //  float WeekDataY[] = {0, 0, 0, 0, 0, 0, 0}, MonthDataY[] = {0, 0, 0, 0, 0, 0, 0}, YearDataY[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    float WeekDataS[] = {0, 0, 0, 0, 0, 0, 0}, MonthDataS[] = {0, 0, 0, 0, 0, 0, 0}, YearDataS[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int flag = 1;//标识选择的是1-week,2-month,3-year,0-null
    String WeekMode[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    String WeekFlag[]={" "," "," "," "," "," "," "}, MonthFlag[]={" "," "," "," "," "," "," "}, YearFlag[]={" "," "," "," "," "," "," "," "," "," "," "," "};
    TextView weekTv, monthTv, yearTv;
    Handler mHandler;
    //左上角状态栏
    private ImageView iv_wifi, iv_bluetooth,ModeImg;
    private TextView tv_date,tv_time,ModeTv;

    private ImageView img_back;
    private ImageView imv_user_current_photo;
    private TextView tv_user_current_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_skin_info);

        mLineChart = (LineChart) findViewById(R.id.skin_info);
        LineData mLineData = getLineData();
        showChart(mLineChart, mLineData, Color.rgb(0, 0, 0));//114, 188, 223

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0x1:
                        LineData mLineData = getLineData();
                        showChart(mLineChart, mLineData, Color.rgb(0, 0, 0));//114, 188, 223
                        break;
                }
            }
        };


        initData();
        initLayout();
        //刷新界面左上角的时间,1分钟刷新1次时间
        refreshTime();
        RefreshWifiBlue();

    }


    private void initLayout() {
        showMode();
        img_back= (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SkinInfoActivity.this.finish();
            }
        });
        imv_user_current_photo= (ImageView) findViewById(R.id.imv_user_current_photo);
        imv_user_current_photo.setImageBitmap(new Utils(SkinInfoActivity.this).string2Btimap(AppRunning.instance().user_current_photo_position));
        tv_user_current_name= (TextView) findViewById(R.id.tv_user_current_name);
        tv_user_current_name.setText(UserManage_2.instance().searchUserInfo(AppRunning.instance().SelectUserId).name);

        userInfo = UserManage_2.instance().searchUserInfo(AppRunning.instance().SelectUserId);
        weekTv = (TextView) findViewById(R.id.muscle_week);
        weekTv.setOnClickListener(this);
        monthTv = (TextView) findViewById(R.id.muscle_month);
        monthTv.setOnClickListener(this);
        yearTv = (TextView) findViewById(R.id.muscle_year);
        yearTv.setOnClickListener(this);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_date= (TextView) findViewById(R.id.tv_date);
        tv_date.setText(DateString.getDate(0));  //获取当前时间
        iv_wifi = (ImageView) findViewById(R.id.iv_wifi);
//        iv_usb = (ImageView) findViewById(R.id.iv_usb);
//        iv_weaather = (ImageView) findViewById(R.id.iv_weaather);
        iv_bluetooth = (ImageView) findViewById(R.id.iv_bluetooth);
        //左上角天气图片
//        SharedPreferences preferences = getSharedPreferences("todayWeather", Context.MODE_PRIVATE);
//        int img = preferences.getInt("pic", 0);
//        iv_weaather.setImageResource(AppRunning.WeatherImages[img]);
    }

    /*
    * 获取要是显示的数据
    * */
    private void initData() {
        String urlY = null,urlS = null;
        if(mode.equals("skinFace")){
            urlY = AppConst.GetBodyInfoUrl + "?userid=" + AppRunning.instance().SelectUserId + "&type="+"OiLInFace";
            urlS = AppConst.GetBodyInfoUrl + "?userid=" + AppRunning.instance().SelectUserId + "&type="+"WaterInFace";
        }else if(mode.equals("skinHand")){
            urlY = AppConst.GetBodyInfoUrl + "?userid=" + AppRunning.instance().SelectUserId + "&type="+"OiLInHand";
            urlS = AppConst.GetBodyInfoUrl + "?userid=" + AppRunning.instance().SelectUserId + "&type="+"WaterInHand";
        }
        //new GetYDataTask(urlY).execute();
        new GetSDataTask(urlS).execute();

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.muscle_week:
                if (flag != 1) {
                    weekTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn));
                    if (flag == 2) {
                        monthTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn_an));
                    } else if (flag == 3) {
                        yearTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn_an));
                    }
                    flag = 1;
                    LineData mLineData = getLineData();
                    showChart(mLineChart, mLineData, Color.rgb(0, 0, 0));//114, 188, 223
                }
                break;
            case R.id.muscle_month:
                if (flag != 2) {
                    monthTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn));
                    if (flag == 1) {
                        weekTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn_an));
                    } else if (flag == 3) {
                        yearTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn_an));
                    }

                    flag = 2;
                    LineData mLineData = getLineData();
                    showChart(mLineChart, mLineData, Color.rgb(0, 0, 0));//114, 188, 223
                }
                break;
            case R.id.muscle_year:
                if (flag != 3) {
                    yearTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn));
                    if (flag == 1) {
                        weekTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn_an));
                    } else if (flag == 2) {
                        monthTv.setBackground(getResources().getDrawable(R.drawable.muscle_btn_an));
                    }
                    flag = 3;
                    LineData mLineData = getLineData();
                    showChart(mLineChart, mLineData, Color.rgb(0, 0, 0));//114, 188, 223
                }
                break;
        }
    }


    class GetSDataTask extends AsyncTask<Void, Void, String> {

        String url;

        public GetSDataTask(String url) {
            this.url = url;
        }

        @Override
        protected String doInBackground(Void... voids) {
            String result = "";
            try {
                result = HttpUtils.Get(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result == null || result.equals("")) {
                Toast.makeText(SkinInfoActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject json = new JSONObject(result);
                    if (json.getInt("operationstatus") == 1) {
//                        Toast.makeText(SkinInfoActivity.this,"获取数据成功",Toast.LENGTH_SHORT).show();
                        JSONArray jsonArray = json.getJSONArray("WeekData");
                        int j=6;
                        for (int i = 0; i < 7; i++) {
                            if(jsonArray.getJSONObject(i).getString("num")==null||jsonArray.getJSONObject(i).getString("num").equals("null")){
                                WeekDataS[j--] =0f;
                            }else{
                                WeekDataS[j--] = Float.valueOf(jsonArray.getJSONObject(i).getString("num"));
                            }

                        }
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date(System.currentTimeMillis()));
                        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                        dayOfWeek--;
                        j=6;
                        for (int i = 0; i < 7; i++) {
                            WeekFlag[j--] = WeekMode[dayOfWeek];
                            if (dayOfWeek == 0) {
                                dayOfWeek = 6;
                            } else {
                                dayOfWeek--;
                            }
                        }
                        JSONArray jsonArray1 = json.getJSONArray("MonthData");
                        j=6;
                        for (int i = 0; i < 7; i++) {
                            if(jsonArray1.getJSONObject(4 * i).getString("num")==null||jsonArray1.getJSONObject(4 * i).getString("num").equals("null")){
                                MonthDataS[j]=0f;
                            }else{
                                MonthDataS[j] = Float.valueOf(jsonArray1.getJSONObject(4 * i).getString("num"));
                            }
                            MonthFlag[j--] = jsonArray1.getJSONObject(4*i).getString("date").substring(8,10);
                        }
                        JSONArray jsonArray2 = json.getJSONArray("YearData");
                        Log.e("year",jsonArray2.toString());
                        j=11;
                        for(int i=0;i<12;i++){
                            if(jsonArray2.getJSONObject(i).getString("num")==null||jsonArray2.getJSONObject(i).getString("num").equals("null")){
                                YearDataS[j] = Float.valueOf(jsonArray2.getJSONObject(i).getString("num"));
                            }else{
                                YearFlag[j--] = jsonArray2.getJSONObject(i).getString("date").substring(5,7);
                            }
                        }
                        Message msg = new Message();
                        msg.what = 1;
                        mHandler.sendMessage(msg);
                    } else {
                        Toast.makeText(SkinInfoActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    Toast.makeText(SkinInfoActivity.this,"工程师正在努力修改",Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void showMode(){

        ModeImg = (ImageView) findViewById(R.id.mode_img);
        ModeTv = (TextView) findViewById(R.id.mode_text);

        if(mode.equals("skinFace")){//脸部肌肤
            ModeImg.setImageResource(R.drawable.icon_water);
            ModeTv.setText("脸部肌肤");
        }else if(mode.equals("skinHand")){//手部肌肤
            ModeImg.setImageResource(R.drawable.icon_water);
            ModeTv.setText("身体肌肤");
        }
    }

    // 设置显示的样式
    private void showChart(LineChart lineChart, LineData lineData, int color) {
        if(lineChart==null){
            Log.e("yasin","line null");
        }else{
            Log.e("yasin","line not null");
        }

        lineChart.setDrawBorders(false);  //是否在折线图上添加边框

        //lineChart.getAxisRight().setEnabled(false);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        lineChart.getXAxis().setTextColor(Color.WHITE);
        lineChart.getXAxis().setTextSize(16f);//x轴

        lineChart.getLegend().setTextSize(16f);


        // no description text
        lineChart.setDescription("");// 数据描述
        // 如果没有数据的时候,会显示这个,类似listview的emtpyview
        lineChart.setNoDataTextDescription("You need to provide data for the chart.");

        // enable / disable grid background
        lineChart.getAxisLeft().setEnabled(true);
        lineChart.getAxisLeft().setDrawGridLines(true);
        lineChart.getAxisLeft().setTextColor(Color.WHITE);

        lineChart.setDrawGridBackground(false); // 是否显示表格颜色
        lineChart.setGridBackgroundColor(Color.WHITE & 0x70FFFFFF); // 表格的的颜色,在这里是是给颜色设置一个透明度

        // enable touch gestures
        lineChart.setTouchEnabled(false); // 设置是否可以触摸

        // enable scaling and dragging
        lineChart.setDragEnabled(false);// 是否可以拖拽
        lineChart.setScaleEnabled(false);// 是否可以缩放

        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(false);//

       lineChart.setBackgroundColor(Color.TRANSPARENT);// 设置背景


        // add data
        lineChart.setData(lineData); // 设置数据

        // get the legend (only possible after setting data)
        Legend mLegend = lineChart.getLegend(); // 设置比例图标示,就是那个一组y的value的

        // modify the legend ...
        // mLegend.setPosition(LegendPosition.LEFT_OF_CHART);
        mLegend.setForm(Legend.LegendForm.CIRCLE);// 样式
        mLegend.setFormSize(6f);// 字体
        mLegend.setTextColor(Color.WHITE);// 颜色
//      mLegend.setTypeface(mTf);// 字体

        lineChart.animateX(0); // 立即执行的动画,x轴
    }

    /**
     * 生成一个数据
     *
     * @return
     */
    private LineData getLineData() {
        ArrayList<String> xValues = new ArrayList<String>();


        // y轴的数据
        ArrayList<Entry> yValuesS = new ArrayList<Entry>();
        ArrayList<Entry> yValuesY = new ArrayList<Entry>();

        if(flag==1){
            for (int i = 0; i < 7; i++) {
                yValuesS.add(new Entry(WeekDataS[i], i));
               // yValuesY.add(new Entry(WeekDataY[i], i));
                xValues.add(WeekFlag[i]);
            }
            xValues.add("");
        }else if(flag==2){
            for (int i = 0; i < 7; i++) {
                yValuesS.add(new Entry(MonthDataS[i], i));
              //  yValuesY.add(new Entry(MonthDataY[i], i));
                xValues.add(MonthFlag[i]);
            }
            xValues.add("");
        }else if(flag==3){
            for (int i = 0; i < 12; i++) {
                yValuesS.add(new Entry(YearDataS[i], i));
               // yValuesY.add(new Entry(YearDataY[i], i));
                xValues.add(YearFlag[i]);
            }
            xValues.add("");
        }


        // create a dataset and give it a type
        // y轴的数据集合
        LineDataSet lineDataSet = new LineDataSet(yValuesS, "肌肤水份" /*显示在比例图上*/);
        // mLineDataSet.setFillAlpha(110);
        // mLineDataSet.setFillColor(Color.RED);

        //用y轴的集合来设置参数
        lineDataSet.setLineWidth(1.75f); // 线宽
        lineDataSet.setCircleSize(2f);// 显示的圆形大小
        lineDataSet.setColor(Color.parseColor("#00b7ee"));// 显示颜色
        lineDataSet.setCircleColor(Color.parseColor("#00b7ee"));// 圆形的颜色
        lineDataSet.setCircleColorHole(Color.parseColor("#00b7ee"));
        lineDataSet.setHighLightColor(Color.parseColor("#00b7ee")); // 高亮的线的颜色
        lineDataSet.setValueTextColor(Color.parseColor("#00b7ee"));
        lineDataSet.setValueTextSize(16f);
        //设置曲线平滑
        lineDataSet.setDrawCubic(true);
        lineDataSet.setCircleSize(0.6f);
        //设置填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFillColor(Color.rgb(9,202,214));

//        LineDataSet lineDataSet1 = new LineDataSet(yValuesY, "肌肤油份" /*显示在比例图上*/);
//        lineDataSet1.setValueTextSize(16f);
//        // mLineDataSet.setFillAlpha(110);
//        // mLineDataSet.setFillColor(Color.RED);
//
//        //用y轴的集合来设置参数
//        lineDataSet1.setLineWidth(1.75f); // 线宽
//        lineDataSet1.setCircleSize(2f);// 显示的圆形大小
//        lineDataSet1.setColor(Color.parseColor("#22ff95"));// 显示颜色
//        lineDataSet1.setCircleColor(Color.parseColor("#22ff95"));// 圆形的颜色
//        lineDataSet1.setCircleColorHole(Color.parseColor("#22ff95"));
//        lineDataSet1.setHighLightColor(Color.parseColor("#22ff95")); // 高亮的线的颜色
//        lineDataSet1.setValueTextColor(Color.parseColor("#22ff95"));


        ArrayList<LineDataSet> lineDataSets = new ArrayList<LineDataSet>();
        lineDataSets.add(lineDataSet); // add the datasets
      //  lineDataSets.add(lineDataSet1);

        // create a data object with the datasets
        LineData lineData = new LineData(xValues, lineDataSets);

        return lineData;
    }
}