1 首先在 build.gradle 里导入包

implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

2.新建 启动Activity

LineChartActivity 如下

  1. 1 **
  2. 2 * @Author: Bytezero_zhengLei
  3. 3 * @Time: 2023/3/24 10:12
  4. 4 * @Project_Name: LineChartActivity.java
  5. 5 * @Email: 420498246@qq.com
  6. 6 * @Description:
  7. 7 * @TODO: 折线图
  8. 8 */
  9. 9
  10. 10 public class LineChartActivity extends AppCompatActivity {
  11. 11
  12. 12 private LineChart lineChart;
  13. 13 List<IncomeBean> list = new ArrayList<>();
  14. 14
  15. 15 @Override
  16. 16 protected void onCreate(Bundle savedInstanceState) {
  17. 17 super.onCreate(savedInstanceState);
  18. 18 setContentView(R.layout.activity_line_chart);
  19. 19
  20. 20 lineChart = (LineChart) findViewById(R.id.linechart);
  21. 21
  22. 22 lineChart = MPAndroidUtil.initChart(this, lineChart);
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27 for (int i =0; i <10; i ++){
  28. 28 IncomeBean incomeBean = new IncomeBean(36.5,"2020-01-01 00:00:00");
  29. 29 list.add(incomeBean);
  30. 30
  31. 31 }
  32. 32
  33. 33 // 开始画折线图
  34. 34 setLineChart(list, "BMI" + "kg/²", getResources().getColor(R.color.bule_title));
  35. 35 }
  36. 36
  37. 37
  38. 38 //设置折线
  39. 39
  40. 40
  41. 41 public void setLineChart(List<IncomeBean> mLineChart, String string, int color) {
  42. 42 lineChart = MPAndroidUtil.initChart(this, lineChart);
  43. 43 lineChart.setData(MPAndroidUtil.showLineChart(mLineChart, string, color));
  44. 44 //设置一页最大显示个数为6,超出部分就滑动
  45. 45 float ratio = (float) mLineChart.size() / (float) 6;
  46. 46 //显示的时候是按照多大的比率缩放显示,1f表示不放大缩小
  47. 47 // lineChart.zoom(ratio, 1f, 0, 0);
  48. 48 // 设置填充图
  49. 49 Drawable drawable = getResources().getDrawable(R.drawable.fade_blue);
  50. 50 MPAndroidUtil.setChartFillDrawable(drawable, lineChart);
  51. 51 // 设置点击的弹窗
  52. 52 MPAndroidUtil.setMarkerView1(lineChart);
  53. 53
  54. 54
  55. 55 /* lineChart.getLineData().addDataSet(MPAndroidUtil.addLine(list1, "地位条", getResources().getColor(R.color.text_orange)));
  56. 56 lineChart.invalidate();*/
  57. 57
  58. 58 }
  59. 59 }

3.新建数据 IncomeBean

  1. 1 /**
  2. 2 * @Author: Bytezero_zhengLei
  3. 3 * @Time: 2023/3/24 10:24
  4. 4 * @Project_Name: IncomeBean.java
  5. 5 * @Email: 420498246@qq.com
  6. 6 * @Description:
  7. 7 * @TODO:
  8. 8 */
  9. 9
  10. 10 public class IncomeBean implements Serializable {
  11. 11 public String tradeDate;// 时间
  12. 12 public double value;// 数值
  13. 13
  14. 14 public IncomeBean(double mValue, String mTradeDate) {
  15. 15 tradeDate = mTradeDate;
  16. 16 value = mValue;
  17. 17 }
  18. 18
  19. 19 @Override
  20. 20 public String toString() {
  21. 21 return "IncomeBean{" +
  22. 22 "tradeDate='" + tradeDate + '\'' +
  23. 23 ", value=" + value +
  24. 24 '}';
  25. 25 }
  26. 26 }

4.制定折线图的属性  MPAndroidUtil

  1. 1 /**
  2. 2 * @Author: Bytezero_zhengLei
  3. 3 * @Time: 2023/3/24 10:20
  4. 4 * @Project_Name: MPAndroidUtil.java
  5. 5 * @Email: 420498246@qq.com
  6. 6 * @Description:
  7. 7 * @TODO:
  8. 8 */
  9. 9
  10. 10 public class MPAndroidUtil {
  11. 11 private static final String TAG = "MPAndroidUtil";
  12. 12 private static XAxis xAxis = null; //X轴
  13. 13 private static YAxis leftYAxis; //左侧Y轴
  14. 14 private static YAxis rightYaxis; //右侧Y轴
  15. 15 private static Legend legend; //图例
  16. 16
  17. 17
  18. 18 /**
  19. 19 * 初始化图表 折线图
  20. 20 */
  21. 21 public static LineChart initChart(Context context, LineChart lineChart) {
  22. 22
  23. 23 /***图表设置***/
  24. 24 //是否展示网格线
  25. 25 lineChart.setDrawGridBackground(false);
  26. 26 //是否显示边界
  27. 27 lineChart.setDrawBorders(false);
  28. 28 //是否可以拖动
  29. 29 lineChart.setDragEnabled(false);
  30. 30 //是否有触摸事件
  31. 31 lineChart.setTouchEnabled(true);
  32. 32 // 关闭双击放大功能
  33. 33 lineChart.setDoubleTapToZoomEnabled(false);
  34. 34 //设置XY轴动画效果
  35. 35 lineChart.animateY(2500);
  36. 36 lineChart.animateX(1500);
  37. 37
  38. 38 lineChart.setBackgroundColor(context.getResources().getColor(R.color.white));
  39. 39
  40. 40
  41. 41 /***XY轴的设置***/
  42. 42 xAxis = null;
  43. 43 xAxis = lineChart.getXAxis();
  44. 44 leftYAxis = lineChart.getAxisLeft();
  45. 45 rightYaxis = lineChart.getAxisRight();
  46. 46 //X轴设置显示位置在底部
  47. 47 xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
  48. 48 xAxis.setAxisMinimum(0f);
  49. 49 xAxis.setGranularity(1f);
  50. 50 //保证Y轴从0开始,不然会上移一点
  51. 51 leftYAxis.setAxisMinimum(0f);
  52. 52 rightYaxis.setAxisMinimum(0f);
  53. 53
  54. 54 // 但还是显示了网格线,而且不是我们想要的 虚线 。其实那是 X Y轴自己的网格线,禁掉即可
  55. 55 xAxis.setDrawGridLines(false);
  56. 56 rightYaxis.setDrawGridLines(false);
  57. 57 leftYAxis.setDrawGridLines(true);
  58. 58 //设置X Y轴网格线为虚线(实体线长度、间隔距离、偏移量:通常使用 0)
  59. 59 leftYAxis.enableGridDashedLine(10f, 10f, 0f);
  60. 60 // 目标效果图没有右侧Y轴,所以去掉右侧Y轴
  61. 61 rightYaxis.setEnabled(false);
  62. 62
  63. 63 /***折线图例 标签 设置***/
  64. 64 legend = lineChart.getLegend();
  65. 65 //legend.setEnabled(false);
  66. 66 //设置显示类型,LINE CIRCLE SQUARE EMPTY 等等 多种方式,查看LegendForm 即可
  67. 67 legend.setForm(Legend.LegendForm.LINE);
  68. 68 legend.setTextSize(12f);
  69. 69 //显示位置 左下方
  70. 70 legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
  71. 71 legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
  72. 72 legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
  73. 73 //是否绘制在图表里面
  74. 74 legend.setDrawInside(false);
  75. 75 // legend.setExtra(mLegendEntries);
  76. 76
  77. 77 // lineChart.setNoDataText(context.getResources().getString(R.string.No_data));
  78. 78 lineChart.setNoDataText(" ");
  79. 79 // 设置右下角的提示
  80. 80 Description description = new Description();
  81. 81 // description.setText("需要展示的内容");
  82. 82 description.setEnabled(false);
  83. 83 lineChart.setDescription(description);
  84. 84
  85. 85 lineChart.setExtraBottomOffset(2 * 8f);
  86. 86
  87. 87 lineChart.setXAxisRenderer(new CustomXAxisRenderer(lineChart.getViewPortHandler(), lineChart.getXAxis(), lineChart.getTransformer(YAxis.AxisDependency.LEFT)));
  88. 88 return lineChart;
  89. 89 }
  90. 90
  91. 91
  92. 92 /**
  93. 93 * 曲线初始化设置 一个LineDataSet 代表一条曲线
  94. 94 *
  95. 95 * @param lineDataSet 线条
  96. 96 * @param color 线条颜色
  97. 97 * @param mode
  98. 98 */
  99. 99 public static LineDataSet initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
  100. 100 lineDataSet.setColor(color);
  101. 101 lineDataSet.setCircleColor(color);
  102. 102 lineDataSet.setLineWidth(1f);
  103. 103 lineDataSet.setCircleRadius(2f);
  104. 104 //设置曲线值的圆点是实心还是空心
  105. 105 lineDataSet.setDrawCircleHole(true);
  106. 106 lineDataSet.setValueTextSize(10f);
  107. 107 //设置折线图填充
  108. 108 lineDataSet.setDrawFilled(true);
  109. 109 lineDataSet.setFormLineWidth(1f);
  110. 110 lineDataSet.setFormSize(15.f);
  111. 111 if (mode == null) {
  112. 112 //设置曲线展示为圆滑曲线(如果不设置则默认折线)
  113. 113 lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
  114. 114 } else {
  115. 115 lineDataSet.setMode(mode);
  116. 116 }
  117. 117 // 不显示值
  118. 118 lineDataSet.setDrawValues(false);
  119. 119 return lineDataSet;
  120. 120
  121. 121 }
  122. 122
  123. 123 public static LineData showLineChart(final List<IncomeBean> dataList, String name, int color) {
  124. 124 List<Entry> entries = new ArrayList<>();
  125. 125 for (int i = 0; i < dataList.size(); i++) {
  126. 126 IncomeBean data = dataList.get(i);
  127. 127 /**
  128. 128 * 在此可查看 Entry构造方法,可发现 可传入数值 Entry(float x, float y)
  129. 129 * 也可传入Drawable, Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
  130. 130 */
  131. 131 Entry entry = new Entry(i, (float) data.value);
  132. 132 entries.add(entry);
  133. 133 }
  134. 134 xAxis.setValueFormatter(new IndexAxisValueFormatter() {
  135. 135 @Override
  136. 136 public String getFormattedValue(float value) {
  137. 137 String tradeDate;
  138. 138 try {
  139. 139 tradeDate = dataList.get((int) value % dataList.size()).tradeDate;
  140. 140 } catch (Exception mE) {
  141. 141 tradeDate = "2020-01-01 00:00:00";
  142. 142 }
  143. 143
  144. 144 return StrToStr("yyyy-MM-dd HH:mm:ss", "MM-dd HH:mm", tradeDate);
  145. 145 }
  146. 146 });
  147. 147
  148. 148
  149. 149 xAxis.setLabelCount(6, false);
  150. 150
  151. 151 leftYAxis.setLabelCount(8);
  152. 152 // 每一个LineDataSet代表一条线
  153. 153 LineDataSet lineDataSet = new LineDataSet(entries, name);
  154. 154 lineDataSet = initLineDataSet(lineDataSet, color, LineDataSet.Mode.CUBIC_BEZIER);
  155. 155 LineData lineData = new LineData(lineDataSet);
  156. 156 return lineData;
  157. 157
  158. 158 }
  159. 159
  160. 160 public static void setMarkerView1(LineChart lineChart) {
  161. 161 // LineChartMarkView1 mv = new LineChartMarkView1(MApplication.getInstance(), xAxis.getValueFormatter());
  162. 162 LineChartMarkView1 mv = new LineChartMarkView1(lineChart.getContext(), xAxis.getValueFormatter());
  163. 163 mv.setChartView(lineChart);
  164. 164 lineChart.setMarker(mv);
  165. 165 lineChart.invalidate();
  166. 166 }
  167. 167
  168. 168
  169. 169 /*
  170. 170 * 设置线条填充背景颜色
  171. 171 *
  172. 172 * @param drawable
  173. 173 */
  174. 174 public static LineChart setChartFillDrawable(Drawable drawable, LineChart mLineChart) {
  175. 175 if (mLineChart.getData() != null && mLineChart.getData().getDataSetCount() > 0) {
  176. 176 LineDataSet lineDataSet = (LineDataSet) mLineChart.getData().getDataSetByIndex(0);
  177. 177 //避免在 initLineDataSet()方法中 设置了 lineDataSet.setDrawFilled(false); 而无法实现效果
  178. 178 lineDataSet.setDrawFilled(true);
  179. 179 lineDataSet.setFillDrawable(drawable);
  180. 180
  181. 181 mLineChart.invalidate();
  182. 182
  183. 183 }
  184. 184 return mLineChart;
  185. 185 }
  186. 186
  187. 187
  188. 188 // 传入某种格式的时间格式,得到特定的时间格式
  189. 189 public static String StrToStr(String SimpleDateFormat_in, String SimpleDateFormat_out, String str) {
  190. 190 SimpleDateFormat format = new SimpleDateFormat(SimpleDateFormat_in);
  191. 191 SimpleDateFormat format1 = new SimpleDateFormat(SimpleDateFormat_out);
  192. 192 Date date = null;
  193. 193 try {
  194. 194 date = format.parse(str);
  195. 195 } catch (ParseException e) {
  196. 196 e.printStackTrace();
  197. 197 }
  198. 198 return format1.format(date.getTime());
  199. 199 }
  200. 200
  201. 201
  202. 202 }

5.LineChartMarkView1

  1. 1 **
  2. 2 * @Author: Bytezero_zhengLei
  3. 3 * @Time: 2023/3/24 10:45
  4. 4 * @Project_Name: LineChartMarkView1.java
  5. 5 * @Email: 420498246@qq.com
  6. 6 * @Description:
  7. 7 * @TODO:
  8. 8 */
  9. 9
  10. 10 public class LineChartMarkView1 extends MarkerView {
  11. 11
  12. 12 private TextView tvDate;
  13. 13 private TextView tvValue;
  14. 14 private IAxisValueFormatter xAxisValueFormatter;
  15. 15 DecimalFormat df = new DecimalFormat(".00");
  16. 16
  17. 17 public LineChartMarkView1(Context context, IAxisValueFormatter xAxisValueFormatter) {
  18. 18 super(context, R.layout.layout_markview1);
  19. 19 this.xAxisValueFormatter = xAxisValueFormatter;
  20. 20
  21. 21 tvDate = findViewById(R.id.tv_date);
  22. 22 tvValue = findViewById(R.id.tv_value);
  23. 23 }
  24. 24
  25. 25 @SuppressLint("SetTextI18n")
  26. 26 @Override
  27. 27 public void refreshContent(Entry e, Highlight highlight) {
  28. 28 Chart chart = getChartView();
  29. 29 if (chart instanceof LineChart) {
  30. 30 LineData lineData = ((LineChart) chart).getLineData();
  31. 31 //获取到图表中的所有曲线
  32. 32 List<ILineDataSet> dataSetList = lineData.getDataSets();
  33. 33 for (int i = 0; i < dataSetList.size(); i++) {
  34. 34 LineDataSet dataSet = (LineDataSet) dataSetList.get(i);
  35. 35 //获取到曲线的所有在Y轴的数据集合,根据当前X轴的位置 来获取对应的Y轴值
  36. 36 float y = dataSet.getValues().get((int) e.getX()).getY();
  37. 37 if (i == 0) {
  38. 38 tvValue.setText(dataSet.getLabel() + ":" + e.getY());
  39. 39 }
  40. 40 }
  41. 41 tvDate.setText(xAxisValueFormatter.getFormattedValue(e.getX(), null));
  42. 42 }
  43. 43
  44. 44 super.refreshContent(e, highlight);
  45. 45 }
  46. 46
  47. 47 @Override
  48. 48 public MPPointF getOffset() {
  49. 49 return new MPPointF(-(getWidth() / 2), -getHeight());
  50. 50
  51. 51 }
  52. 52 }

6.CustomXAxisRenderer

  1. 1 /**
  2. 2 * @Author: Bytezero_zhengLei
  3. 3 * @Time: 2023/3/24 10:23
  4. 4 * @Project_Name: CustomXAxisRenderer.java
  5. 5 * @Email: 420498246@qq.com
  6. 6 * @Description:
  7. 7 * @TODO:
  8. 8 */
  9. 9
  10. 10 public class CustomXAxisRenderer extends XAxisRenderer {
  11. 11 public CustomXAxisRenderer(ViewPortHandler viewPortHandler, XAxis xAxis, Transformer trans) {
  12. 12 super(viewPortHandler, xAxis, trans);
  13. 13 }
  14. 14
  15. 15 @Override
  16. 16 protected void drawLabel(Canvas c, String formattedLabel, float x, float y, MPPointF anchor, float angleDegrees) {
  17. 17 // super.drawLabel(c, formattedLabel, x, y, anchor, angleDegrees);//注释掉这个,否则坐标标签复写两次
  18. 18 String[] lines = formattedLabel.split(" ");
  19. 19 for (int i = 0; i < lines.length; i++) {
  20. 20 float vOffset = i * mAxisLabelPaint.getTextSize();
  21. 21 Utils.drawXAxisValue(c, lines[i], x, y + vOffset, mAxisLabelPaint, anchor, angleDegrees);
  22. 22 }
  23. 23 }
  24. 24 }

5.一些 小的  layout

  1. LineChartMarkView1layout
  1. 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. 2 android:layout_width="wrap_content"
  3. 3 android:layout_height="wrap_content"
  4. 4 android:background="@drawable/shape_square"
  5. 5 android:orientation="vertical">
  6. 6
  7. 7 <TextView
  8. 8 android:id="@+id/tv_date"
  9. 9 android:layout_width="wrap_content"
  10. 10 android:layout_height="wrap_content"
  11. 11 android:textColor="@android:color/white" />
  12. 12
  13. 13 <TextView
  14. 14 android:id="@+id/tv_value"
  15. 15 android:layout_width="wrap_content"
  16. 16 android:layout_height="wrap_content"
  17. 17 android:layout_marginTop="5dp"
  18. 18 android:textColor="@android:color/white" />
  19. 19 </LinearLayout>

6.LineChartActivity中的 layout

  1. 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. 2 xmlns:app="http://schemas.android.com/apk/res-auto"
  3. 3 xmlns:tools="http://schemas.android.com/tools"
  4. 4 android:layout_width="match_parent"
  5. 5 android:layout_height="match_parent"
  6. 6 tools:context=".LineChart.LineChartActivity">
  7. 7
  8. 8 <com.github.mikephil.charting.charts.LineChart
  9. 9 android:layout_gravity="center"
  10. 10 android:id="@+id/linechart"
  11. 11 android:layout_width="match_parent"
  12. 12 android:layout_height="300dp" />
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18 </LinearLayout>

这样就ok了

Android LineChart 折线图Demo的更多相关文章

  1. android绘画折线图二

    紧接着android绘画折线图一,下面来介绍第二种方法,使用该方法,首先需要一个Androidplot-core-0.4.3-release.jar,该jar包之后也包含在项目源码中 建立一个andr ...

  2. android绘画折线图一

    最近需要实现用android来画折线图,所以百度了一下,发现确实很多,也很乱,现在整理两种方法(第二种方法在[android绘画折线图二]中实现),仅供大家参考,一起学习研究. 第一种使用ChartF ...

  3. android 自定义折线图

    看图: 比较简陋,主要是通过canvas画上去的: package com.example.democurvegraph.view; import java.util.ArrayList; impor ...

  4. Android自定义控件-折线图

    好长时间没有更新博客了,终于可以抽出时间写点东西了,写点什么呢?最近在qq群里边有人问,下边的这个控件怎么画?如下图所示:图可以左右拖动,直到显示完全为止.刚开始看到这个效果图,我也想了一下总共分为以 ...

  5. Android自定义折线图

    老师布置了个作业:http://www.cnblogs.com/qingxu/p/5316897.html 作业中提到的 “玩了几天以后,大家发现了一些很有意思的现象,比如黄金点在逐渐地往下移动.” ...

  6. Qwt开发笔记(二):Qwt基础框架介绍、折线图介绍、折线图Demo以及代码详解

    前言   QWT开发笔记系列整理集合,这是目前使用最为广泛的Qt图表类(Qt的QWidget代码方向只有QtCharts,Qwt,QCustomPlot),使用多年,系统性的整理,本系列旨在系统解说并 ...

  7. Echarts 折线图Demo调色12种,可以直接使用~~~

    测试Demo代码~~ <template> <div> <div id="myChart" ref="mapBox" style= ...

  8. jfreechart折线图 demo

    public class ChartUtil { public static ChartUtil chartUtil; private RoomViewsDataService roomViewsDa ...

  9. echarts折线图Demo

    echarts链接:http://echarts.baidu.com/examples/editor.html?c=line-stack 黑底代码:http://gallery.echartsjs.c ...

  10. MPAndroidChart 3.0——LineChart(折线图)

    显示效果 MPAndroidChart每一种图表的基本使用方式都基本相同 了解一种图表的实现 参考项目源码其他的图表也就差不多哩 在布局文件中定义 <com.github.mikephil.ch ...

随机推荐

  1. 一个基于线程池和epoll的IO事件管理器

    前面几篇博客介绍了Epoll, ThreadPool, 其中 Epoll 封装了epoll的各类api, 可在epoll句柄中添加/修改/删除 fd 的 各类事件(EPOLLIN | EPOLLOUT ...

  2. Vue组件template中html代码自动补齐设置

    1.vscode设置==>扩展==>JSON==>在settings.json中编辑 2.在最后 } 前添加如下代码保存文件即可 // 自动补全模板字符串 "emmet.t ...

  3. k8s利用endpoints和service访问外部服务

    一.原理解析 在k8s集群中我们通过创建service去访问对应pod内的服务,而在创建service的时候会同时创建一个与service同名的endpoints对象,endpoints与pod实际建 ...

  4. Java mysql批量关联插入数据

    mysql 关联批量插入数据 INSERT INTO 表1 ( id, name, addTime ) SELECT UUID( ) AS id, v_Name, now( ) FROM 表2;

  5. cesium 入门指南

    最近拿到了几份offer,经过这次找工作发现自己最近脱节挺严重,为了后续的职业发展,决定开始书写博客记录自己的努力. cesium属于 跨平台.跨浏览器的展现三维地球.地图的JavaScript库. ...

  6. python 安装fbprophet模块的艰辛历程

    fbprophet这个模块是我目前见过最难装的一个模块,我安装这个包安装了3天,气死我了,需求的依赖包太多,而且对依赖包的版本有极高的要求,所以建议在装这个模块的时候在一个空的虚拟环境下安装,这样依赖 ...

  7. antv g6 出现 n.addEdge is not a function问题

    问题描述直接上图 解决方式就是将edge里面边的source和target对应的id换成字符串类型就行. 例如: edges: [ { id: 299, source": 3629.toSt ...

  8. CF1338E JYPnation

    题意:给定一个竞赛图,且其中不包含任意一组三元环 $(a, b, c)$,满足 $a \to d$,$b \to d$,$c \to d$,求每个点两两之间的距离之和(若无法达到即为 $614n$). ...

  9. vue中router.resolve

    resolve是router的一个方法, 返回路由地址的标准化版本.该方法适合编程式导航. let router = this.$router.resolve({ path: '/home', que ...

  10. 我的JAVA后端技术选型(2020版)

    JAVA后端技术选型(2020版)集群网关: LVS+keepalived 或 HAProxy服务网关 : zuul1.x注册中心: Eureka,Zookeeper配置中心: Spring Clou ...