在這個項目 我用了三個圖表來顯示java
1.MPAndroidChartandroid
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.git
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() { } } }