Android之MPAndroidChart的动态柱形图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/soha_dong/article/details/80001375

导入MPAndroidChart的jar包以后就写个工具类:

package itsoha.com.tffic.Utils;

import android.content.Context;
import android.graphics.Color;

import com.github.mikephil.charting.charts.BarChart;
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.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;

import java.util.ArrayList;
import java.util.Random;

public class BarEngine {
    private String title;
    private int max;
    private BarChart mChart;

    public BarEngine(String title) {
        this.title = title;
    }

    public BarChart getView(Context context, int max) {
        this.max = max;
        mChart = new BarChart(context);
        mChart.setDescription("");
        mChart.setScaleEnabled(false);

        BarData data = new BarData();
        data.setValueTextColor(Color.BLACK);
        mChart.setData(data);

        Legend legend = mChart.getLegend();
        legend.setTextSize(25f);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setTextColor(Color.BLACK);
        xAxis.setTextSize(25f);
        xAxis.setDrawGridLines(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

        YAxis axisLeft = mChart.getAxisLeft();
        axisLeft.setDrawGridLines(false);
        axisLeft.setAxisMinValue(0);
        axisLeft.setAxisMinValue(max);

        YAxis right = mChart.getAxisRight();
        right.setDrawGridLines(false);

        return mChart;
    }

    public void update(int value) {
        if (value <= 0) {
            value = new Random().nextInt(max);
        }

        BarData data = mChart.getBarData();
        BarDataSet dataSet = data.getDataSetByIndex(0);
        if (dataSet == null) {
            dataSet = creaSet();
            data.addDataSet(dataSet);
        }
        //显示当前时间
        data.addXValue(MyUtils.getCurrentTime());
        BarEntry barEntry = new BarEntry(value,dataSet.getEntryCount());
        data.addEntry(barEntry,0);

        mChart.notifyDataSetChanged();
        mChart.setVisibleXRangeMaximum(5);
        mChart.moveViewToX(mChart.getXValCount()-5);

    }

    private BarDataSet creaSet() {
        BarDataSet dataSet = new BarDataSet(new ArrayList<BarEntry>(), title);
        dataSet.setColor(Color.GREEN);
        dataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        return dataSet;
    }
}

猜你喜欢

转载自blog.csdn.net/soha_dong/article/details/80001375