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>

布局文件中图片

相关推荐
恋猫de小郭35 分钟前
iOS 26 正式版即将发布,Flutter 完成全新 devicectl + lldb 的 Debug JIT 运行支持
android·前端·flutter
幻雨様1 小时前
UE5多人MOBA+GAS 54、用户登录和会话创建请求
android·ue5
Just_Paranoid1 小时前
【SystemUI】锁屏来通知默认亮屏Wake模式
android·framework·systemui·keyguard·aod
没有了遇见1 小时前
Android +,++,+= 的区别
android·kotlin
_无_妄_3 小时前
Android 使用 WebView 直接加载 PDF 文件,通过 JS 实现
android
VomPom3 小时前
手写一个精简版Koin:深入理解依赖注入核心原理
android
IT乐手3 小时前
Java 编写查看调用栈信息
android
Digitally4 小时前
如何轻松永久删除 Android 手机上的短信
android·智能手机
JulyYu5 小时前
Flutter混合栈适配安卓ActivityResult
android·flutter
Warren985 小时前
Appium学习笔记
android·windows·spring boot·笔记·后端·学习·appium