Android MPAndroidChart使用

前言这里使用的是折线图

1.引用

复制代码
 implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

2.工具类

java 复制代码
/**
 * MPAndroidChart
 */
public class ChartLineUtil {

    public static void initChart(Context context, LineChart chart, int lineType) {
        // Chart Style
        {
            // background color
            chart.setBackgroundColor(Color.WHITE);
            // disable description text
            chart.getDescription().setEnabled(false);
            // enable touch gestures
            chart.setTouchEnabled(true);
//            // set listeners
//            chart.setOnChartValueSelectedListener(this);
//            chart.setDrawGridBackground(false);

            // create marker to display box when values are selected
            MyMarkerView mv = new MyMarkerView(context, R.layout.chart_custom_marker_view, lineType);

            // Set the marker to the chart
            mv.setChartView(chart);
            chart.setMarker(mv);

            // enable scaling and dragging
            chart.setDragEnabled(true);
            chart.setScaleEnabled(true);
            // chart.setScaleXEnabled(true);
            // chart.setScaleYEnabled(true);

            // force pinch zoom along both axis
            chart.setPinchZoom(true);
        }
        // draw points over time
        chart.animateX(100);
        // X-Axis Style
        XAxis xAxis;
        {
            xAxis = chart.getXAxis();
            // vertical grid lines
//            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.setDrawGridLines(false);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); // 设置X轴的位置
            xAxis.setAxisMinimum(0);
            xAxis.setLabelCount(16);
            xAxis.setAxisMaximum(80);
//            xAxis.setValueFormatter(new DecimalXAxisValueFormatter(2)); // 显示两位小数

        }

        //Y-Axis Style
        YAxis yAxis;
        {
            yAxis = chart.getAxisLeft();
            // disable dual axis (only use LEFT axis)
            chart.getAxisRight().setEnabled(false);
            // horizontal grid lines
            yAxis.enableGridDashedLine(10f, 10f, 0f);
            // axis range
            if (lineType == 1) {
                yAxis.setAxisMaximum(50f);
                yAxis.setAxisMinimum(0f);
            } else {
                yAxis.setAxisMaximum(12f);
                yAxis.setAxisMinimum(0f);
            }

        }
    }

    /**
     * 给图表设置数据
     *
     * @param chart    控件
     * @param values   数据
     * @param lineType 线类型  1:压力   2:流速
     */
    public static void setChartData(LineChart chart, List<Entry> values, int lineType) {
        int Red = Color.parseColor("#FC2A69");
        int Yellow = Color.parseColor("#0053DB");
        LineDataSet set1;
        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            set1.setValues(values);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(values, "");
            set1.setAxisDependency(YAxis.AxisDependency.LEFT);
            set1.setColor(lineType == 1 ? Red : Yellow);
            set1.setCircleColor(lineType == 1 ? Red : Yellow);
            set1.setLineWidth(2f);
            set1.setCircleRadius(1f);
            set1.setFillAlpha(56);
            set1.setFillColor(lineType == 1 ? Red : Yellow);
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setDrawCircleHole(false);

            // create a data object with the data sets
            LineData data = new LineData(set1);
            //不显示曲线点的具体数值
            data.setDrawValues(false);
            //不显示图例
            chart.getLegend().setEnabled(false);

            // set data
            chart.setData(data);
        }
    }

    /**
     * 添加数据
     */
    public static void addChartData(LineChart chart, int total, float value, int lineType) {
        LineDataSet set1;
        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
            List<Entry> values = set1.getValues();
            values.add(new Entry((float) ArithUtil.mul(total - 1, 0.05), value));
            // 保持最多1600个数据点
            if (values.size() > 1600) {
                values.remove(0);
                // 调整所有x值,使它们从0开始
                for (Entry entry : values) {
                    double sub = ArithUtil.sub(entry.getX(), 0.05); //3秒一条数据,X轴单位min
                    entry.setX((float) sub);
                }
            }
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
            chart.invalidate(); // refresh
        }

    }

    /**
     * 清除数据
     */
    public static void clearChartData(LineChart chart,int lineType){
        chart.clearValues();
        chart.setScaleMinima(1.0f, 1.0f);
        chart.getViewPortHandler().refresh(new Matrix(), chart, true);
        setChartData(chart, new ArrayList<>(), lineType);
    }
}

3.布局文件

复制代码
chart_custom_marker_view
复制代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:background="@drawable/marker2"
    tools:ignore="Overdraw">

    <TextView
        android: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:textSize="12sp"
        android:textColor="@android:color/white"
        android:ellipsize="end"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>

布局文件中图片

相关推荐
怪兽20148 小时前
Handler中有Loop死循环,为什么没有阻塞主线程,原理是什么?
android·面试
雨白9 小时前
掌握协程的边界与环境:CoroutineScope 与 CoroutineContext
android·kotlin
木易 士心9 小时前
Android 开发核心知识体系与面试指南精简版
android·面试·职场和发展
一棵树735110 小时前
Android OpenGL ES初窥
android·大数据·elasticsearch
初级代码游戏10 小时前
MAUI劝退:安卓实体机测试
android
奔跑中的蜗牛66611 小时前
直播APP跨平台架构实践(二):KMP UI 与 Rust 下载引擎协作实践
android
沐怡旸11 小时前
【底层机制】【Android】AIDL原理与实现机制详解
android·面试
小仙女喂得猪11 小时前
2025 跨平台方案KMP,Flutter,RN之间的一些对比
android·前端·kotlin
2501_9151063211 小时前
iOS 混淆与 IPA 加固全流程,多工具组合实现无源码混淆、源码防护与可审计流水线(iOS 混淆|IPA 加固|无源码加固|App 防反编译)
android·ios·小程序·https·uni-app·iphone·webview
游戏开发爱好者811 小时前
用多工具组合把 iOS 混淆做成可复用的工程能力(iOS混淆 IPA加固 无源码混淆 Ipa Guard)
android·ios·小程序·https·uni-app·iphone·webview