趋势图
博客专区 > lsy999 的博客 > 博客详情
趋势图
lsy999 发表于5个月前
趋势图
  • 发表于 5个月前
  • 阅读 6
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

在这个项目 我用了三个图表来显示

1.MPAndroidChart

package com.intentpumin.lsy.intentpumin;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.intentpumin.lsy.intentpumin.http.HttpUtil;
import com.intentpumin.lsy.intentpumin.logic.MainLogic;
import com.intentpumin.lsy.intentpumin.tools.Add_eqpt;
import com.intentpumin.lsy.intentpumin.tools.Add_stat;
import com.intentpumin.lsy.intentpumin.tools.StataValueResult;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.finalteam.okhttpfinal.RequestParams;
import cn.finalteam.okhttpfinal.StringHttpRequestCallback;

public class ChartAdminActivity extends AppCompatActivity {
    //趋势图
    private LineChart mChart;
    private TextView tv_ss;

    //日期
    Button et_yunxing;
    //获取日期格式器对象
    DateFormat fmtDate = new java.text.SimpleDateFormat("yyyy-MM-dd");

    //定义一个TextView控件对象
    TextView sdate = null;
    TextView edate = null;
    //获取一个日历对象
    Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);


    //需要查询的设备ID集合
    List<String> eqptIds = new ArrayList<>();

    //需要查询的状态集合
    List<String> statIds = new ArrayList<>();


    Map<Add_eqpt, List<Add_stat>> resData = new LinkedHashMap<>();



    //当点击DatePickerDialog控件的设置按钮时,调用该方法
//    DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
//        @Override
//        public void onDateSet(DatePicker view, int year, int monthOfYear,
//                              int dayOfMonth) {
//            //修改日历控件的年,月,日
//            //这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
//            dateAndTime.set(Calendar.YEAR, year);
//            dateAndTime.set(Calendar.MONTH, monthOfYear);
//            dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
//            //将页面TextView的显示更新为最新时间
//            upDateDate();
//        }
//    };
    TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {

        //同DatePickerDialog控件
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
            dateAndTime.set(Calendar.MINUTE, minute);
            upDateTime();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_char);
        init();
        initChart();
    }

    private void init() {
        tv_ss = (TextView) findViewById(R.id.tv_ss);
        tv_ss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                requestData();
            }
        });
        sdate = (TextView) findViewById(R.id.tv_date_start);
        //折线图控件//趋势图
        //日期
        sdate.setClickable(true);
        sdate.setFocusable(true);
        edate = (TextView) findViewById(R.id.tv_date_end);
        edate.setClickable(true);
        edate.setFocusable(true);
        et_yunxing = (Button) findViewById(R.id.et_yunxing);
        et_yunxing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent inter = getIntent();
                inter.setClass(ChartAdminActivity.this, AdminSSActivity.class);
                startActivityForResult(inter, 100);
            }
        });

        sdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog dateDlg = new DatePickerDialog(ChartAdminActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                                dateAndTime.set(Calendar.YEAR, year);
                                dateAndTime.set(Calendar.MONTH, monthOfYear);
                                dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                sdate.setText(fmtDate.format(dateAndTime.getTime()));

                            }
                        },
                        dateAndTime.get(Calendar.YEAR),
                        dateAndTime.get(Calendar.MONTH),
                        dateAndTime.get(Calendar.DAY_OF_MONTH));

                dateDlg.show();

            }
        });
        edate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog dateDlg = new DatePickerDialog(ChartAdminActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                dateAndTime.set(Calendar.YEAR, year);
                                dateAndTime.set(Calendar.MONTH, monthOfYear);
                                dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                edate.setText(fmtDate.format(dateAndTime.getTime()));
                            }
                        },
                        dateAndTime.get(Calendar.YEAR),
                        dateAndTime.get(Calendar.MONTH),
                        dateAndTime.get(Calendar.DAY_OF_MONTH));
                dateDlg.show();
            }
        });
        upDateDate();
        upDateTime();


    }

    private void upDateDate() {
        sdate.setText(fmtDate.format(dateAndTime.getTime()));
    }

    private void upDateTime() {
        edate.setText(fmtDate.format(dateAndTime.getTime()));
    }

    //初始化MPchart
    private Highlight[] temp0 = new Highlight[]{new Highlight(4, 1), new Highlight(4, 0)};

    private void setHight(int dataSetIndex, Highlight h) {
        for (int i = 0; i < temp0.length; i++) {
            if (temp0[i].getDataSetIndex() == dataSetIndex) {
                temp0[i] = h;
            }
        }
        mChart.highlightValues(temp0);
    }

    private void initChart() {
        mChart = (LineChart) findViewById(R.id.charts);
        mChart.setDrawGridBackground(false);
        mChart.setDescription("");
        mChart.setNoDataTextDescription("You need to provide data for the chart.");
        mChart.setTouchEnabled(true);
        mChart.setDragEnabled(false);
        mChart.setScaleEnabled(false);
        mChart.setPinchZoom(false);
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.removeAllLimitLines();
        leftAxis.setLabelCount(5, true);
      /*  // 设置在Y轴上是否是从0开始显示
        leftAxis.setStartAtZero(true);*/
        leftAxis.setTextColor(0xffcccccc);
        leftAxis.setDrawGridLines(true);
        leftAxis.setDrawGridLines(true);
        mChart.getAxisLeft().setEnabled(true);
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextSize(8f);
        xAxis.setTextColor(0xffcccccc);
        xAxis.setDrawLabels(true);
        xAxis.setLabelsToSkip(0);
        YAxis axisRight = mChart.getAxisRight();
        axisRight.setEnabled(true);
        axisRight.setDrawGridLines(false);
        axisRight.setDrawLabels(false);
        mChart.getAxisRight().setEnabled(false);
        //setData(null);
        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);

        // set the marker to the chart
        mChart.setMarkerView(mv);

        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();
        // modify the legend ...
        // l.setPosition(LegendPosition.LEFT_OF_CHART);
        l.setForm(Legend.LegendForm.LINE);
        l.setEnabled(false);
        // // dont forget to refresh the drawing
        mChart.invalidate();
       /* mChart.highlightValue(1, 1);*/
        // mChart.highlightValue(0, 1);
        mChart.highlightValues(temp0);
        mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
                setHight(dataSetIndex, h);
            }

            @Override
            public void onNothingSelected() {

            }
        });

    }

   /* private void setData(List<Data_Bean> list) {

        ArrayList<String> xVals = new ArrayList<String>();
        ArrayList<Entry> yVals = new ArrayList<Entry>();
        if (list == null || list.size() == 0) {
            xVals.add("0");
            yVals.add(new Entry(0, 0));
        } else {
            for (int i = 0; i < list.size(); i++) {
                xVals.add(list.get(i).getDate());
                yVals.add(new Entry(Float.valueOf(list.get(i).getR_value()), i));
            }

        }
        LineDataSet set1 = new LineDataSet(yVals, "");
        set1.setColor(getResources().getColor(R.color.bg_color));
        set1.setCircleColor(getResources().getColor(R.color.white));
        set1.setLineWidth(1f);
        set1.setCircleRadius(3f);
        set1.setDrawCircleHole(false);
        set1.setValueTextSize(9f);
        set1.setFillColor(getResources().getColor(R.color.transparent));
        set1.setFillAlpha(0);
        set1.setDrawFilled(true);
        //相当于隐藏
        set1.setHighLightColor(getResources().getColor(R.color.transparent));

        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        dataSets.add(set1); // add the datasets
        LineData data = new LineData(xVals, dataSets);
        // set data
        mChart.setData(data);

    *//*    //模拟点击,最后一个显示marker
        int px = (int) Util.dip2px(BaseApp.getInstance(), 15);
        setSimulateClick(mChart, -px, px);*//*

    }*/

    //折线图控件//趋势图
    private void requestData(List<String> eqptIds, List<String> statIds) {

        final String s_date = sdate.getText().toString().trim();
        System.out.print(sdate.getText().toString().trim());
        final String e_date = edate.getText().toString().trim();
        System.out.print(edate.getText().toString().trim());
        RequestParams params = new RequestParams();
        params.addFormDataPart("signature", "1");
        params.addFormDataPart("s_date",s_date);
        params.addFormDataPart("e_date",e_date);
       //params.addFormDataPart("eqpt_id", "47875318-1A24-2B35-2783-AE19D7334E2D,47875318-1A24-2B35-2783-AE19D7334E2D");
          params.addFormDataPart("eqpt_id", parseMaker(eqptIds));
        //   params.addFormDataPart("stat_id", "E3BF0082-AC49-9C56-C3D3-18EE8B31ECC9" +
               // ",C82CF813-76AC-1C58-6163-79F33F4AC323");
       params.addFormDataPart("stat_id", parseMaker(statIds));


        HttpUtil.getInstance().post(MainLogic.GET_VALUE, params, new StringHttpRequestCallback() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            protected void onSuccess(String s) {
                Gson gson = new Gson();
                Type type = new TypeToken<StataValueResult>() {
                }.getType();
                StataValueResult result = gson.fromJson(s, type);
                System.out.println(s);
                // 这里
                if (result.getRes() == 1) {
                    //setData(result.getData().get(0).getData());
                    Toast.makeText(getApplicationContext(), "后台获取数据成功", Toast.LENGTH_SHORT).show();
                    mChart.invalidate();

                } else {
                    Toast.makeText(getApplicationContext(), result.getMsg(), Toast.LENGTH_SHORT).show();

                }

            }

            //初始化MPchart
            private Highlight[] temp0 = new Highlight[]{new Highlight(4, 1), new Highlight(4, 0)};

            //
            private void setHight(int dataSetIndex, Highlight h) {
                for (int i = 0; i < temp0.length; i++) {
                    if (temp0[i].getDataSetIndex() == dataSetIndex) {
                        temp0[i] = h;
                    }
                }
                mChart.highlightValues(temp0);
            }

           /* private void setData(List<Data_Bean> list) {

                ArrayList<String> xVals = new ArrayList<String>();
                ArrayList<Entry> yVals = new ArrayList<Entry>();
                if (list == null || list.size() == 0) {
                    xVals.add("0");
                    yVals.add(new Entry(0, 0));
                } else {
                    for (int i = 0; i < list.size(); i++) {
                        xVals.add(list.get(i).getDate().substring(5, 10));
                        yVals.add(new Entry(Float.valueOf(list.get(i).getR_value()), i));
                    }

                }
                LineDataSet set1 = new LineDataSet(yVals, "");
                set1.setColor(getResources().getColor(R.color.bg_color));
                set1.setCircleColor(getResources().getColor(R.color.white));
                set1.setLineWidth(1f);
                set1.setCircleRadius(3f);
                set1.setDrawCircleHole(false);
                set1.setValueTextSize(9f);
                set1.setFillColor(getResources().getColor(R.color.transparent));
                set1.setFillAlpha(0);
                set1.setDrawFilled(true);
                //相当于隐藏
                set1.setHighLightColor(getResources().getColor(R.color.transparent));

                ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
                dataSets.add(set1); // add the datasets
                LineData data = new LineData(xVals, dataSets);
                // set data
                mChart.setData(data);

    *//*    //模拟点击,最后一个显示marker
        int px = (int) Util.dip2px(BaseApp.getInstance(), 15);
        setSimulateClick(mChart, -px, px);*//*

            }

            private void setSimulateClick(View view, float x, float y) {
                long downTime = SystemClock.uptimeMillis();
                final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
                        MotionEvent.ACTION_DOWN, x, y, 0);
                downTime += 1000;
                final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
                        MotionEvent.ACTION_UP, x, y, 0);
                view.onTouchEvent(downEvent);
                view.onTouchEvent(upEvent);
                downEvent.recycle();
                upEvent.recycle();
            }*/

            public void onFailure(int errorCode, String msg) {
                System.out.println("error code " + errorCode + "\nmsg " + msg);
            }



            public void onFinish() {
                //结束刷新
                System.out.println("完成");
            }
        });
    }

    //设备信息
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 100 && resultCode == 101) {

            resData = (Map<Add_eqpt, List<Add_stat>>) data.getBundleExtra("ids").getSerializable("checkList");
            System.out.println("add_eqpt selected size is " + resData.size());
            eqptIds.clear();
            statIds.clear();


            for (Map.Entry<Add_eqpt, List<Add_stat>> entry : resData.entrySet()) {
                for (Add_stat stat : entry.getValue()) {
                    eqptIds.add(entry.getKey().getEqpt_id());
                    statIds.add(stat.getStat_id());
                }
            }
            if (eqptIds.size() > 0) {
                requestData(eqptIds, statIds);
            }

        }
    }

    /**
     * 参数构造
     *
     * @return
     */
    public String parseMaker(List<String> parseList) {
        StringBuffer strParse = new StringBuffer();
        for (String s : parseList) {
            strParse.append(s + ",");
        }
        return strParse.toString().subSequence(0, strParse.length() - 1).toString();
    }

}
二.XCL-char在实例图里面

1.

package com.intentpumin.lsy.intentpumin.chart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

import com.intentpumin.lsy.intentpumin.R;
import com.intentpumin.lsy.intentpumin.tools.StataValueResult;

import org.xclcharts.chart.CustomLineData;
import org.xclcharts.chart.PointD;
import org.xclcharts.chart.SplineChart;
import org.xclcharts.chart.SplineData;
import org.xclcharts.common.IFormatterTextCallBack;
import org.xclcharts.event.click.PointPosition;
import org.xclcharts.renderer.XEnum;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class SplineChart03View extends DemoView {

    private SplineChart chart = new SplineChart();

    //分类轴标签集合
    //日期轴
    private LinkedList<String> labels = new LinkedList<String>();
    //数据轴
    private LinkedList<SplineData> chartDate = new LinkedList<SplineData>();
    //点击显示轴
    private Paint mPaintTooltips = new Paint(Paint.ANTI_ALIAS_FLAG);

    //Splinechart支持横向和竖向定制线
    private List<CustomLineData> mXCustomLindateset = new ArrayList<CustomLineData>();
    private List<CustomLineData> yXCustomLindateset = new ArrayList<CustomLineData>();

    public SplineChart03View(Context context) {
        super(context);
        initView();
    }

    public SplineChart03View(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public SplineChart03View(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    private void initView() {
        chart.setCategoryAxisMax(100);
        chart.setCategoryAxisMin(10);
        chartDataSet();
        chartLabels();
        chartRender();
        //绑定手势滑动事件
        this.bindTouch(this, chart);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //图所占范围大小
        chart.setChartRange(w, h);
    }

    private void chartRender() {
        try {

            int[] ltrb = getBarLnDefaultSpadding();
            chart.setPadding(ltrb[0], ltrb[1], ltrb[2], ltrb[3]);

            //显示边框
            chart.showRoundBorder();

            //数据源
            chart.setCategories(labels);
            chart.setDataSource(chartDate);

            //坐标系
            //数轴轴最大值
            chart.getDataAxis().setAxisMax(100);
            chart.getDataAxis().setAxisMin(0);

            //数据轴刻度间隔
            chart.getDataAxis().setAxisSteps(10);
            chart.setCustomLines(yXCustomLindateset);//x轴

//标签轴最大值
            chart.getDataAxis().setAxisMax(100);
            chart.getDataAxis().setAxisMin(0);

            //数据轴刻度间隔
            chart.getDataAxis().setAxisSteps(10);
            chart.setCustomLines(mXCustomLindateset);//y轴

            //設置背景顏色
            chart.setApplyBackgroundColor(true);
            chart.setBackgroundColor(R.color.colorPrimary);
            chart.getBorder().setBorderLineColor(R.color.colorAccent);

            //调轴线与网格线风格
            chart.getCategoryAxis().hideTickMarks();
            chart.getDataAxis().hideAxisLine();
            chart.getDataAxis().hideTickMarks();
            chart.getPlotGrid().showHorizontalLines();

            chart.getCategoryAxis().getAxisPaint().setColor(chart.getPlotGrid().getHorizontalLinePaint().getColor());
            chart.getCategoryAxis().getAxisPaint().setStrokeWidth(chart.getPlotGrid().getHorizontalLinePaint().getStrokeWidth());

            chart.setDotLabelFormatter(new IFormatterTextCallBack() {
                @Override
                public String textFormatter(String value) {
                    String label = "[" + value + "]";
                    return (label);
                }
            });
//标题
            chart.setTitle("浦敏科技");

            //点击激活监听
            chart.ActiveListenItemClick();
            //为了让触发更灵敏,可以扩大5px的点击监听范围
            chart.extPointClickRange(5);
            chart.showClikedFocus();

            //显示平滑曲线
            chart.setCrurveLineStyle(XEnum.CrurveLineStyle.BEZIERCURVE);

            //图例显示子啊正下方
            chart.getPlotLegend().setVerticalAlign(XEnum.VerticalAlign.BOTTOM);
            chart.getPlotLegend().setHorizontalAlign(XEnum.HorizontalAlign.CENTER);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Main", e.toString());

        }
    }

    private void chartDataSet() {
    }

    //x轴
    private void chartLabels() {
        labels.add("12");
    }

    private int lineLables = 0;

    public void setData(StataValueResult result) {
       /* List<String> inlabels = new ArrayList<>();
        for (DataBean data : result.getData()) {
            int abels = 0;
            if (data != null) {
                List<PointD> inlabel = new ArrayList<PointD>();
                //泛型 <>
                for (Data_Bean dataPoint : data.getData()) {
                    abels += 10;
                    //inlabels.add(new PointD(abels, Double.parseDouble(date.getDate())));
                    inlabels.add(dataPoint.getDate2());
                }
                labels.clear();
                labels.addAll(inlabels);
            }
        }
        int lineIndex = 0;

        for (DataBean lineData : result.getData()) {
            int index = 0;
            lineIndex++;
            switch (lineIndex) {
                case 1:

                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    break;
            }

            if (lineData != null) {
                List<PointD> linePoint = new ArrayList<PointD>();
                for (Data_Bean dataPoint : lineData.getData()) {
                    index += 10;
                    linePoint.add(new PointD(index, Double.parseDouble(dataPoint.getR_value())));

                }

                SplineData dataSeries = new SplineData("线", linePoint,
                        getContext().getResources().getColor(R.color.black_overlay));

                chartDate.add(dataSeries);
            }
        }
*/
    }

    @Override
    public void render(Canvas canvas) {
        super.render(canvas);
        try {
            chart.render(canvas);
        } catch (Exception e) {
            Log.e("Main", e.toString());
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        if (event.getAction() == MotionEvent.ACTION_UP) {
            triggerClick(getX(), getY());
        }
        return true;
    }

    //触发监听
    private void triggerClick(float x, float y) {
        if (!chart.getListenItemClickStatus()) return;

        PointPosition record = chart.getPositionRecord(x, y);
        if (null == record) return;

        if (record.getDataID() >= chartDate.size()) return;
        SplineData lData = chartDate.get(record.getDataID());
        List<PointD> linePoint = lData.getLineDataSet();
        int pos = record.getDataChildID();
        int i = 0;
        Iterator it = linePoint.iterator();
        while (it.hasNext()) {
            PointD entry = (PointD) it.next();

            if (pos == i) {
                Double xValue = entry.x;
                Double yValue = entry.y;

                float r = record.getRadius();
                chart.showFocusPointF(record.getPosition(), r + r * 0.8f);
                chart.getFocusPaint().setStyle(Style.FILL);
                chart.getFocusPaint().setStrokeWidth(3);
                if (record.getDataID() >= 2) {
                    chart.getFocusPaint().setColor(Color.BLUE);
                } else {
                    chart.getFocusPaint().setColor(Color.RED);
                }
                //在点击处显示tooltip
                mPaintTooltips.setColor(Color.RED);
                chart.getToolTip().setCurrentXY(x, y);
                chart.getToolTip().addToolTip(" Key:" + lData.getLineKey(), mPaintTooltips);
                chart.getToolTip().addToolTip(
                        " Current Value:" + Double.toString(xValue) + "," + Double.toString(yValue), mPaintTooltips);
                chart.getToolTip().getBackgroundPaint().setAlpha(100);
                this.invalidate();

                break;
            }
            i++;
        }
    }

}
三 HelloChart
package com.pumin.lsy;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.pumin.lsy.demolsychart.R;
import com.pumin.lsy.http.OkHttpUtils;
import com.pumin.lsy.tools.DataBean;
import com.pumin.lsy.tools.ItemsBean;
import com.pumin.lsy.tools.LineDataResult;
import com.pumin.lsy.tools.Rustatvalue;
import com.pumin.lsy.ui.SplineChart03View;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.LineChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.LineChartView;


/**
 * Created by yang on 2016/5/30.
 */
public class TestActivity extends AppCompatActivity {
 private LineChartView lineChartView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        responseDate();
        //mSpline = (SplineChart03View) findViewById(R.id.chart);
        lineChartView= (LineChartView) findViewById(R.id.charts);
        lineChartView.setZoomType(ZoomType.HORIZONTAL);
        /** Note: Chart is within ViewPager so enable container scroll mode. **/
        lineChartView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
    }

    private void responseDate() {
        final Map<String, String> map = new HashMap<>();
        map.put("s_date", "2016-05-07");
        map.put("e_date", "2016-05-13");
        map.put("eqpt_id", "47875318-1A24-2B35-2783-AE19D7334E2D,47875318-1A24-2B35-2783-AE19D7334E2D,47875313-1A24-2B35-2783-AE19D7334E2D");
        map.put("signature", "1");
        map.put("stat_id", "E3BF0082-AC49-9C56-C3D3-18EE8B31ECC9,C82CF813-76AC-1C58-6163-79F33F4AC323,E3BF0082-AC49-9C56-C3D3-18EE8B31ECC9");
        OkHttpUtils.post(url, new OkHttpUtils.ResultCallback() {
            @Override
            public void onSuccess(Object response) {
                Log.i("result", response.toString());

                Rustatvalue dataResult = JSON.parseObject(response.toString(), Rustatvalue.class);
                List<DataBean> datas = dataResult.getData();
                lineChartView.setLineChartData(generateLineChartData(datas));
            }

            @Override
            public void onFailure(Exception e) {

            }
        }, map);
    }
    private LineChartData generateLineChartData(List<DataBean> datas) {
        //构建20个点的数据
        List<Line> lines = new ArrayList<>();
        // value.
        Axis distanceAxis = new Axis();
        for (int index = 0; index < datas.size(); index++) {
            List<PointValue> values = new ArrayList<>();
            List<String> dates = new ArrayList<>();
            DataBean itemData = datas.get(index);
            List<ItemsBean> itemsData = itemData.getItems();
            for (int i = 0; i < itemsData.size(); i++) {
                String rValue = "".equals(itemsData.get(index).getItem().getR_value()) ? "0" : itemsData
                        .get(index).getItem().getR_value();
                values.add(new PointValue(i, (float) Double.parseDouble(rValue)));
               Log.d("key", "value = " + rValue);
                String date = itemsData.get(index).getDate();
                dates.add(date);
            }
            distanceAxis.setValues(getAxisValues(itemsData));
            Line line = new Line(values);
            if (index == 1) {
                line.setColor(getResources().getColor(R.color.red));
            } else {
                line.setColor(getResources().getColor(R.color.yellow));
            }
            lines.add(line);
        }


        LineChartData data = new LineChartData(lines);

        // value.
//        distanceAxis.setName("Distance");
        //设置底部x轴字体的颜色
        distanceAxis.setTextColor(ChartUtils.COLOR_ORANGE);
        distanceAxis.setMaxLabelChars(1);

        distanceAxis.setHasLines(true);
        distanceAxis.setHasTiltedLabels(true);
        distanceAxis.setName("   ");
        //设置底部
        data.setAxisXBottom(distanceAxis);

        data.setAxisYLeft(new Axis().setName("Axis Y").setHasLines(true));
        return data;

    }

    //初始化x轴的值
    public List<AxisValue> getAxisValues(List<ItemsBean> hours) {
        int numSubcolumns = 1;
        List<AxisValue> axisValues = new ArrayList<>();
        for (int i = 0; i < hours.size(); ++i) {

            for (int j = 0; j < numSubcolumns; j++) {
                axisValues.add(new AxisValue(i, getFormatDate(hours.get(i).getDate()).toCharArray()));
            }
        }
        return axisValues;
    }


    private String getFormatDate(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-HH-dd");
        try {
            Date newDate = simpleDateFormat.parse(date);
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH-dd");
            return dateFormat.format(newDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    private class ValueTouchListener implements
            LineChartOnValueSelectListener {

        @Override
        public void onValueSelected(int lineIndex, int pointIndex,
                                    PointValue value) {
        }
        @Override
        public void onValueDeselected() {
        }
    }
}
共有 人打赏支持
粉丝 0
博文 66
码字总数 23713
×
lsy999
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: