一、添加依赖
Usage

allprojects {repositories {maven { url 'https://jitpack.io' }}
}

App level build.gradle(在app的build.gradle中添加依赖)

dependencies {implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
}

二、layout布局,我这里实现了三个图形,可以根据自己的需要,添加图形控件

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_horizontal"android:text="柱形图" /><com.github.mikephil.charting.charts.BarChartandroid:id="@+id/chart1"android:layout_width="match_parent"android:layout_height="400dp"android:layout_margin="10dp"android:padding="20dp" /><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_horizontal"android:text="水平柱形图" /><com.github.mikephil.charting.charts.HorizontalBarChartandroid:id="@+id/hBarChart"android:layout_width="match_parent"android:layout_height="400dp"android:layout_margin="10dp"android:background="@android:color/white"android:padding="20dp" /><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_horizontal"android:text="折线图" /><com.github.mikephil.charting.charts.LineChartandroid:id="@+id/lineChart"android:layout_width="match_parent"android:layout_height="400dp"android:layout_margin="10dp"android:padding="20dp" /></LinearLayout>
</ScrollView>

三、实现代码
图形横纵坐标默认为float形式,如果想展示文字形式,需要自定义适配器。自定义适配器会在“四”中列出

public class FifteenActivity extends AppCompatActivity implementsOnChartValueSelectedListener {private String[] mMonths = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"};private String[] mParties = new String[]{"Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G", "Party H","Party I", "Party J", "Party K", "Party L", "Party M", "Party N", "Party O", "Party P","Party Q", "Party R", "Party S", "Party T", "Party U", "Party V", "Party W", "Party X","Party Y", "Party Z"};private Typeface mTfRegular;private Typeface mTfLight;protected BarChart mChart;private HorizontalBarChart hBarChart;private LineChart lineChart;@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_fifteen_layout);mTfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");mChart = findViewById(R.id.chart1);hBarChart = findViewById(R.id.hBarChart);lineChart = findViewById(R.id.lineChart);initBarChart();initHBarChart();initLineChart();}/*** 初始化柱形图控件属性*/private void initBarChart() {mChart.setOnChartValueSelectedListener(this);mChart.setDrawBarShadow(false);mChart.setDrawValueAboveBar(true);mChart.getDescription().setEnabled(false);// if more than 60 entries are displayed in the chart, no values will be// drawnmChart.setMaxVisibleValueCount(60);// scaling can now only be done on x- and y-axis separatelymChart.setPinchZoom(false);mChart.setDrawGridBackground(false);//        IAxisValueFormatter xAxisFormatter = new DayAxisValueFormatter(mChart);//自定义坐标轴适配器,配置在X轴,xAxis.setValueFormatter(xAxisFormatter);IAxisValueFormatter xAxisFormatter = new XAxisValueFormatter();XAxis xAxis = mChart.getXAxis();xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);xAxis.setTypeface(mTfLight);//可以去掉,没什么用xAxis.setDrawAxisLine(false);xAxis.setGranularity(1f);xAxis.setValueFormatter(xAxisFormatter);//自定义坐标轴适配器,配置在Y轴。leftAxis.setValueFormatter(custom);IAxisValueFormatter custom = new MyAxisValueFormatter();//设置限制临界线LimitLine limitLine = new LimitLine(3f, "临界点");limitLine.setLineColor(Color.GREEN);limitLine.setLineWidth(1f);limitLine.setTextColor(Color.GREEN);//获取到图形左边的Y轴YAxis leftAxis = mChart.getAxisLeft();leftAxis.addLimitLine(limitLine);leftAxis.setTypeface(mTfLight);//可以去掉,没什么用leftAxis.setLabelCount(8, false);leftAxis.setValueFormatter(custom);leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);leftAxis.setSpaceTop(15f);leftAxis.setAxisMinimum(0f);//获取到图形右边的Y轴,并设置为不显示mChart.getAxisRight().setEnabled(false);//图例设置Legend legend = mChart.getLegend();legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);legend.setDrawInside(false);legend.setForm(Legend.LegendForm.SQUARE);legend.setFormSize(9f);legend.setTextSize(11f);legend.setXEntrySpace(4f);//如果点击柱形图,会弹出pop提示框.XYMarkerView为自定义弹出框XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);mv.setChartView(mChart);mChart.setMarker(mv);setBarChartData();}/*** 初始化水平柱形图图控件属性*/private void initHBarChart() {hBarChart.setOnChartValueSelectedListener(this);hBarChart.setDrawBarShadow(false);hBarChart.setDrawValueAboveBar(true);hBarChart.getDescription().setEnabled(false);// if more than 60 entries are displayed in the chart, no values will be// drawnhBarChart.setMaxVisibleValueCount(60);// scaling can now only be done on x- and y-axis separatelyhBarChart.setPinchZoom(false);// draw shadows for each bar that show the maximum value// mChart.setDrawBarShadow(true);hBarChart.setDrawGridBackground(false);//自定义坐标轴适配器,设置在X轴DecimalFormatter formatter = new DecimalFormatter();XAxis xl = hBarChart.getXAxis();xl.setPosition(XAxis.XAxisPosition.BOTTOM);xl.setTypeface(mTfLight);xl.setLabelRotationAngle(-45f);xl.setDrawAxisLine(true);xl.setDrawGridLines(false);xl.setGranularity(1f);
//        xl.setAxisMinimum(0);xl.setValueFormatter(formatter);//对Y轴进行设置YAxis yl = hBarChart.getAxisLeft();yl.setTypeface(mTfLight);yl.setDrawAxisLine(true);yl.setDrawGridLines(true);yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)
//        yl.setInverted(true);hBarChart.getAxisRight().setEnabled(false);//图例设置Legend l = hBarChart.getLegend();l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);l.setOrientation(Legend.LegendOrientation.HORIZONTAL);l.setDrawInside(false);l.setFormSize(8f);l.setXEntrySpace(4f);setHBarChartData();hBarChart.setFitBars(true);hBarChart.animateY(2500);}/*** 初始化折线图控件属性*/private void initLineChart() {lineChart.setOnChartValueSelectedListener(this);lineChart.getDescription().setEnabled(false);lineChart.setBackgroundColor(Color.WHITE);//自定义适配器,适配于X轴IAxisValueFormatter xAxisFormatter = new XAxisValueFormatter();XAxis xAxis = lineChart.getXAxis();xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);xAxis.setTypeface(mTfLight);xAxis.setGranularity(1f);xAxis.setValueFormatter(xAxisFormatter);//自定义适配器,适配于Y轴IAxisValueFormatter custom = new MyAxisValueFormatter();YAxis leftAxis = lineChart.getAxisLeft();leftAxis.setTypeface(mTfLight);leftAxis.setLabelCount(8, false);leftAxis.setValueFormatter(custom);leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);leftAxis.setSpaceTop(15f);leftAxis.setAxisMinimum(0f);lineChart.getAxisRight().setEnabled(false);setLineChartData();}private float getRandom(float range, float startsfrom) {return (float) (Math.random() * range) + startsfrom;}@Overridepublic void onValueSelected(Entry e, Highlight h) {}@Overridepublic void onNothingSelected() {}private void setBarChartData() {ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();//在这里设置自己的数据源,BarEntry 只接收float的参数,//图形横纵坐标默认为float形式,如果想展示文字形式,需要自定义适配器,yVals1.add(new BarEntry(0, 4));yVals1.add(new BarEntry(1, 2));yVals1.add(new BarEntry(2, 6));yVals1.add(new BarEntry(3, 1));BarDataSet set1;if (mChart.getData() != null &&mChart.getData().getDataSetCount() > 0) {set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);set1.setValues(yVals1);mChart.getData().notifyDataChanged();mChart.notifyDataSetChanged();} else {set1 = new BarDataSet(yVals1, "The year 2017");set1.setDrawIcons(false);ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();dataSets.add(set1);BarData data = new BarData(dataSets);data.setValueTextSize(10f);data.setValueTypeface(mTfLight);//可以去掉,没什么用data.setBarWidth(0.9f);mChart.setData(data);}}/*** 设置水平柱形图数据的方法*/private void setHBarChartData() {//填充数据,在这里换成自己的数据源ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();yVals1.add(new BarEntry(0, 4));yVals1.add(new BarEntry(1, 2));yVals1.add(new BarEntry(2, 6));yVals1.add(new BarEntry(3, 1));BarDataSet set1;if (hBarChart.getData() != null &&hBarChart.getData().getDataSetCount() > 0) {set1 = (BarDataSet) hBarChart.getData().getDataSetByIndex(0);set1.setValues(yVals1);hBarChart.getData().notifyDataChanged();hBarChart.notifyDataSetChanged();} else {set1 = new BarDataSet(yVals1, "DataSet 1");set1.setDrawIcons(false);ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();dataSets.add(set1);BarData data = new BarData(dataSets);data.setValueTextSize(10f);data.setValueTypeface(mTfLight);//可以去掉,没什么用data.setBarWidth(0.5f);hBarChart.setData(data);}}/*** 设置折线图的数据*/private void setLineChartData() {//填充数据,在这里换成自己的数据源List<Entry> valsComp1 = new ArrayList<>();List<Entry> valsComp2 = new ArrayList<>();valsComp1.add(new Entry(0, 2));valsComp1.add(new Entry(1, 4));valsComp1.add(new Entry(2, 0));valsComp1.add(new Entry(3, 2));valsComp2.add(new Entry(0, 2));valsComp2.add(new Entry(1, 0));valsComp2.add(new Entry(2, 4));valsComp2.add(new Entry(3, 2));//这里,每重新new一个LineDataSet,相当于重新画一组折线//每一个LineDataSet相当于一组折线。比如:这里有两个LineDataSet:setComp1,setComp2。//则在图像上会有两条折线图,分别表示公司1 和 公司2 的情况.还可以设置更多LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1 ");setComp1.setAxisDependency(YAxis.AxisDependency.LEFT);setComp1.setColor(getResources().getColor(R.color.light_blue));setComp1.setDrawCircles(false);setComp1.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2 ");setComp2.setAxisDependency(YAxis.AxisDependency.LEFT);setComp2.setDrawCircles(true);setComp2.setColor(getResources().getColor(R.color.red));setComp2.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);List<ILineDataSet> dataSets = new ArrayList<>();dataSets.add(setComp1);dataSets.add(setComp2);LineData lineData = new LineData(dataSets);lineChart.setData(lineData);lineChart.invalidate();}public static void startActivity(Context context) {Intent intent = new Intent();intent.setClass(context, FifteenActivity.class);context.startActivity(intent);}
}

四、自定义适配器类
XAxisValueFormatter:

public class XAxisValueFormatter implements IAxisValueFormatter {private String[] xStrs = new String[]{"春", "夏", "秋", "冬"};@Overridepublic String getFormattedValue(float value, AxisBase axis) {int position = (int) value;if (position >= 4) {position = 0;}return xStrs[position];}

MyAxisValueFormatter:

public class MyAxisValueFormatter implements IAxisValueFormatter {private DecimalFormat mFormat;public MyAxisValueFormatter() {mFormat = new DecimalFormat("###,###,###,##0.000");}@Overridepublic String getFormattedValue(float value, AxisBase axis) {return mFormat.format(value) + " $";}
}

DecimalFormatter:

public class DecimalFormatter implements IAxisValueFormatter {private DecimalFormat format;public DecimalFormatter() {format = new DecimalFormat("###,###,##0.00");}@Overridepublic String getFormattedValue(float value, AxisBase axis) {return format.format(value) + "$";}
}

五、自定义MarkerView

public class XYMarkerView extends MarkerView {private TextView tvContent;private IAxisValueFormatter xAxisValueFormatter;private DecimalFormat format;public XYMarkerView(Context context, IAxisValueFormatter xAxisValueFormatter) {super(context, R.layout.custom_marker_view);this.xAxisValueFormatter = xAxisValueFormatter;tvContent = findViewById(R.id.tvContent);format = new DecimalFormat("###.000");}@Overridepublic void refreshContent(Entry e, Highlight highlight) {tvContent.setText("x:" + xAxisValueFormatter.getFormattedValue(e.getX(), null) + ",y:" + format.format(e.getY()));super.refreshContent(e, highlight);}@Overridepublic MPPointF getOffset() {return new MPPointF(-(getWidth() / 2), -getHeight());}
}

custom_marker_view:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content"android:layout_height="40dp"android:background="@drawable/marker2" ><TextViewandroid:id="@+id/tvContent"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_marginTop="7dp"android:layout_marginLeft="5dp"android:layout_marginRight="5dp"android:text="asdf"android:textSize="12dp"android:textColor="@android:color/white"android:ellipsize="end"android:singleLine="true"android:textAppearance="?android:attr/textAppearanceSmall" /></RelativeLayout>

六、这里只实现了些基本功能,更多的API使用,请查看官方文档
demo下载地址:https://github.com/XiaoWuLibs/MyDemo

demo中是本人自己的练习demo,会有很多功能。主页会有很多按钮,btn15是统计图对应的代码。如有需要,请自行查看。

官方文档:https://github.com/PhilJay/MPAndroidChart

MPAndroidChart中文文档下载地址:https://download.csdn.net/download/android157/11188758

由于csdn的机制,一篇文章被多次下载就会增加下载积分,所以,新建五个副本,大家下载的时候挑选积分低的下载

MPAndroidChart中文文档下载地址副本1:https://download.csdn.net/download/android157/11214720

MPAndroidChart中文文档下载地址副本2:https://download.csdn.net/download/android157/11214726

MPAndroidChart中文文档下载地址副本3:https://download.csdn.net/download/android157/11214727

MPAndroidChart中文文档下载地址副本4:https://download.csdn.net/download/android157/11214732

MPAndroidChart中文文档下载地址副本5:https://download.csdn.net/download/android157/11214741

博客:https://blog.csdn.net/koma025/article/details/53886832

设置多组y值:https://blog.csdn.net/u011125199/article/details/52797439

修改源代码:https://blog.csdn.net/dt235201314/article/details/70142117

在github上,你运行起来,首页有很多按钮,应该是btn15 是对应的demo,你找一找。GitHub地址:https://github.com/XiaoWuLibs/MyDemo

具体代码这篇文章讲的超级详细!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Android移动开发之【Android实战项目】DAY5-MPAndroidChart可滑动折线图相关推荐

  1. android studio开发工具介绍,Android应用开发之Android开发工具介绍、Android Studio配置...

    本文将带你了解Android应用开发之Android开发工具介绍.Android Studio配置,希望本文对大家学Android有所帮助. 2.1   Android Studio配置 2.1.1 ...

  2. android final参数,Android应用开发之Android Jetpack-Navigation 使用中参数的传递方法

    本文将带你了解Android应用开发之Android Jetpack-Navigation 使用中参数的传递方法,希望本文对大家学Android有所帮助. 由于使用了Navigation,导致Frag ...

  3. android中base64加密,Android应用开发之android自带Base64加密解密

    本文将带你了解Android应用开发之android自带Base64加密解密,希望本文对大家学Android有所帮助. android项目引用不到以下两个java类 import sun.misc.B ...

  4. 镜像处理坐标 android,Android应用开发之Android重写ImageView实现图片镜像效果的代码教程...

    本文将带你了解Android应用开发之Android重写ImageView实现图片镜像效果的代码教程,希望本文对大家学Android有所帮助. 前两天朋友问我一个问题,如何实现从手机系统相册加载一张图 ...

  5. Android关掉多个activity,Android应用开发之Android Activity栈管理 制定关闭某一个Activity,关闭所有Activit...

    本文将带你了解Android应用开发之Android Activity栈管理  制定关闭某一个Activity,关闭所有Activit,希望本文对大家学Android有所帮助. 系统Api :打开新的 ...

  6. android图片保存形式,Android应用开发之Android ScrollView截图和图片保存到相册的方式...

    本文将带你了解Android应用开发之Android ScrollView截图和图片保存到相册的方式,希望本文对大家学Android有所帮助. 1.1首先来看你一种截取屏幕,这种代码有缺陷,只能截取一 ...

  7. android 开发art,Android应用开发之Android 系统启动原理(art 虚拟机)

    本文将带你了解Android应用开发之Android 系统启动原理(art 虚拟机),希望本文对大家学Android有所帮助. Android   系统启动原理(art 虚拟机) 一.虚拟机的启动 A ...

  8. android 电量详情,Android应用开发之Android 8.0 电池-)耗电详情获取方法

    本文将带你了解Android应用开发之Android 8.0 电池-)耗电详情获取方法,希望本文对大家学Android有所帮助. Android 8.0 电池-)耗电详情获取方法 主要介绍UI位置和基 ...

  9. android 接口实现方法,Android应用开发之Android 请求网络接口实现方法

    本文将带你了解Android应用开发之Android 请求网络接口实现方法,希望本文对大家学Android有所帮助. public   class Fragment01 extends Fragmen ...

最新文章

  1. Eclipse使用Tomcat发布项目时出现YadisException异常解决方案
  2. python工程师月薪多少-Python工程师的薪资到底有多高
  3. C# 正则表达式过滤危险HTML
  4. 《铲子骑士》:“复古游戏”的集大成者
  5. linux 关机 日志,centos7 异常关机了,怎么查看系统的异常日志?
  6. php代码质量怎么提高,如何提高PHP代码的质量?第一部分 自动化工具
  7. 正则表达式与扩展正则表达式区别
  8. 无人驾驶三 卡尔曼滤波及无迹卡尔曼滤波的几何意义
  9. 震惊!程序员一夜赚1W,没想到他就做了这个..........
  10. 为什么优酷的《楚乔传》画质更清晰?独家解密窄带高清技术
  11. 一道简单的题学到的东西
  12. Pandas 安装到Pycharm
  13. 推荐]该内存不能为“read”或“written”的解决方案!
  14. CCS+JS绘制星型拓扑图(关系图)
  15. 计算机的硬盘配额如何更改,磁盘配额怎么设置
  16. 计算机操作系统存在的意义,电脑操作系统的作用
  17. JS中对象按属性排序(冒泡排序)
  18. vue3在控制台打印相关变量的值
  19. XCode 苹果开发者账号,无法本地编译项目,问题所在 The app identifier “xxxx“ cannot be registered to your development team
  20. Network Slimming

热门文章

  1. 深入浅出K-Means算法
  2. parse() got an unexpected keyword argument 'transport_encoding'
  3. 暗通道去雾算法 python实现
  4. OpenMp使用例子
  5. ubuntu 安装OpenBLAS
  6. 组播路由协议基础——组播分发树
  7. c语言中getc与gets,getc()和gets()的用法
  8. 日期格式化为yyyymmdd_大厂日期时间处理最佳实践
  9. 整数数组查找java_使用Java编写程序以查找整数数组中的第一个非重复数字?
  10. php中网页加入音乐,PHP网站插入音乐