安卓集中营程序员技术栈Android应用开发那些事

第三方开源库之 MPAndroidChart

2020-06-28  本文已影响0人  Kevin_小飞象

目前版本 3.1.0
GitHub 地址:https://github.com/PhilJay/MPAndroidChart

简介

使用

  1. 在工程的 build.gradle 中添加如下:
allprojects {
    repositories {
        ...
        maven { url "https://www.jitpack.io" }
    }
}
  1. 在 app/build.gradle 添加如下依赖:
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

折线图(LineChart)

管理类(LineChartManager.java)

public class LineChartManager {
    private LineChart lineChart;
    private YAxis leftAxis;
    private YAxis rightAxis;
    private XAxis xAxis;
    private LineData lineData;
    private LineDataSet lineDataSet;
    private List<ILineDataSet> lineDataSets = new ArrayList<>();
    private SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式  
    private List<String> timeList = new ArrayList<>(); //存储x轴的时间

    //一条曲线
    public LineChartManager(LineChart mLineChart, String name, int color) {
        this.lineChart = mLineChart;
        leftAxis = lineChart.getAxisLeft();
        rightAxis = lineChart.getAxisRight();
        xAxis = lineChart.getXAxis();
        initLineChart();
        initLineDataSet(name, color);
    }

    //多条曲线
    public LineChartManager(LineChart mLineChart, List<String> names, List<Integer> colors) {
        this.lineChart = mLineChart;
        leftAxis = lineChart.getAxisLeft();
        rightAxis = lineChart.getAxisRight();
        xAxis = lineChart.getXAxis();
        initLineChart();
        initLineDataSet(names, colors);
    }

    /**
     * 初始化LineChar
     */
    private void initLineChart() {

        lineChart.setDrawGridBackground(false);
        //显示边界
        lineChart.setDrawBorders(true);
        //折线图例 标签 设置
        Legend legend = lineChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(11f);
        //显示位置
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        legend.setDrawInside(false);

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(10);


        //保证Y轴从0开始,不然会上移一点
        leftAxis.setAxisMinimum(0f);
        rightAxis.setAxisMinimum(0f);
    }

    /**
     * 初始化折线(一条线)
     *
     * @param name
     * @param color
     */
    private void initLineDataSet(String name, int color) {

        lineDataSet = new LineDataSet(null, name);
        lineDataSet.setLineWidth(1.5f);
        lineDataSet.setCircleRadius(1.5f);
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setHighLightColor(color);
        //设置曲线填充
        lineDataSet.setDrawFilled(false);
        lineDataSet.setDrawValues(false);
        lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        lineDataSet.setValueTextSize(10f);
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        //添加一个空的 LineData
        lineData = new LineData();
        lineChart.setData(lineData);
        lineChart.invalidate();

    }

    /**
     * 初始化折线(多条线)
     *
     * @param names
     * @param colors
     */
    private void initLineDataSet(List<String> names, List<Integer> colors) {

        for (int i = 0; i < names.size(); i++) {
            lineDataSet = new LineDataSet(null, names.get(i));
            lineDataSet.setColor(colors.get(i));
            lineDataSet.setLineWidth(1.5f);
            lineDataSet.setCircleRadius(1.5f);
            lineDataSet.setColor(colors.get(i));

            lineDataSet.setDrawFilled(false);
            lineDataSet.setDrawValues(false);
            lineDataSet.setCircleColor(colors.get(i));
            lineDataSet.setHighLightColor(colors.get(i));
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
            lineDataSet.setValueTextSize(10f);
            lineDataSets.add(lineDataSet);

        }
        //添加一个空的 LineData
        lineData = new LineData();
        lineChart.setData(lineData);
        lineChart.invalidate();
    }

    /**
     * 动态添加数据(一条折线图)
     *
     * @param number
     */
    public void addEntry(int number) {

        //最开始的时候才添加 lineDataSet(一个lineDataSet 代表一条线)
        if (lineDataSet.getEntryCount() == 0) {
            lineData.addDataSet(lineDataSet);
        }
        lineChart.setData(lineData);
        //避免集合数据过多,及时清空(做这样的处理,并不知道有没有用,但还是这样做了)
        if (timeList.size() > 11) {
            timeList.clear();
        }

        timeList.add(df.format(System.currentTimeMillis()));

        Entry entry = new Entry(lineDataSet.getEntryCount(), number);
        lineData.addEntry(entry, 0);
        //通知数据已经改变
        lineData.notifyDataChanged();
        lineChart.notifyDataSetChanged();
        //设置在曲线图中显示的最大数量
        lineChart.setVisibleXRangeMaximum(10);
        //移到某个位置
        lineChart.moveViewToX(lineData.getEntryCount() - 5);
    }

    /**
     * 动态添加数据(多条折线图)
     *
     * @param numbers
     */
    public void addEntry(List<Float> numbers) {

        if (lineDataSets.get(0).getEntryCount() == 0) {
            lineData = new LineData(lineDataSets);
            lineChart.setData(lineData);
        }
        if (timeList.size() > 100) {
            timeList.clear();
        }
        timeList.add(df.format(System.currentTimeMillis()));
        for (int i = 0; i < numbers.size(); i++) {
            Entry entry = new Entry(lineDataSet.getEntryCount(), numbers.get(i));
            lineData.addEntry(entry, i);
            lineData.notifyDataChanged();
            lineChart.notifyDataSetChanged();
            lineChart.setVisibleXRangeMaximum(6);
            lineChart.moveViewToX(lineData.getEntryCount() - 5);
        }
    }

    /**
     * 设置Y轴值
     *
     * @param max
     * @param min
     * @param labelCount
     */
    public void setYAxis(float max, float min, int labelCount) {
        if (max < min) {
            return;
        }
        leftAxis.setAxisMaximum(max);
        leftAxis.setAxisMinimum(min);
        leftAxis.setLabelCount(labelCount, false);

        rightAxis.setAxisMaximum(max);
        rightAxis.setAxisMinimum(min);
        rightAxis.setLabelCount(labelCount, false);
        lineChart.invalidate();
    }

    /**
     * 设置高限制线
     *
     * @param high
     * @param name
     */
    public void setHightLimitLine(float high, String name, int color) {
        if (name == null) {
            name = "高限制线";
        }
        LimitLine hightLimit = new LimitLine(high, name);
        hightLimit.setLineWidth(4f);
        hightLimit.setTextSize(10f);
        hightLimit.setLineColor(color);
        hightLimit.setTextColor(color);
        leftAxis.addLimitLine(hightLimit);
        lineChart.invalidate();
    }

    /**
     * 设置低限制线
     *
     * @param low
     * @param name
     */
    public void setLowLimitLine(int low, String name) {
        if (name == null) {
            name = "低限制线";
        }
        LimitLine hightLimit = new LimitLine(low, name);
        hightLimit.setLineWidth(4f);
        hightLimit.setTextSize(10f);
        leftAxis.addLimitLine(hightLimit);
        lineChart.invalidate();
    }

    /**
     * 设置描述信息
     *
     * @param str
     */
    public void setDescription(String str) {
        Description description = new Description();
        description.setText(str);
        lineChart.setDescription(description);
        lineChart.invalidate();
    }
}

一条曲线

  1. 效果图


    01.png
  1. 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/line_chart"
        android:layout_width="match_parent"
        android:layout_height="320dp"/>

    <Button
        android:onClick="addEntry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="随机数"/>

</LinearLayout>
  1. 代码
public class MainActivity extends AppCompatActivity {
    private LineChart mLineChart;

    private LineChartManager mChartManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mChartManager = new LineChartManager(mLineChart,"sensors",Color.BLACK);
    }

    private void initView() {
        mLineChart = findViewById(R.id.line_chart);
    }

    public void addEntry(View view) {
        mChartManager.addEntry((int)(Math.random() * 100));
    }
}

饼图

  1. 效果图


    haha.png
  2. 布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/pie_chart"
        android:layout_width="300dp"
        android:layout_height="300dp"/>

</LinearLayout>
  1. 代码
public class MainActivity extends AppCompatActivity {
    private PieChart mPieChart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initPieChart(mPieChart);
    }

    private void initPieChart(PieChart pieChart) {
        List<PieEntry> strings = new ArrayList<>();
        strings.add(new PieEntry(30f,"男生"));
        strings.add(new PieEntry(70f,"女生"));
        PieDataSet dataSet = new PieDataSet(strings,"");

        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(Color.RED);
        colors.add(Color.BLUE);
        dataSet.setColors(colors);

        PieData pieData = new PieData(dataSet);
        pieData.setDrawValues(true);
        pieData.setValueFormatter(new PercentFormatter(pieChart));
        pieData.setValueTextSize(12f);
        pieData.setValueTextColor(Color.WHITE);

        Description description = new Description();
        description.setText("");
        pieChart.setDescription(description);
        pieChart.setHoleRadius(0f);
        pieChart.setTransparentCircleRadius(0f);
        pieChart.setUsePercentValues(true);

        pieChart.setData(pieData);
        pieChart.invalidate();
    }

    private void initView() {
        mPieChart = findViewById(R.id.pie_chart);
    }
}

柱状图

  1. 效果图


    33.png
  2. 布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <com.github.mikephil.charting.charts.BarChart
        android:id="@+id/bar_chart"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>

</LinearLayout>
  1. 代码
public class MainActivity extends AppCompatActivity {
    private BarChart mBarChart;
    private List<BarEntry> mBarEntries;
    private BarData mBarData;
    private BarDataSet mBarDataSet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initBarEntries();
        initBarData();
    }

    private void initView() {
        mBarChart = findViewById(R.id.bar_chart);
        mBarChart.setNoDataText("正在初始化...");
    }

    private void initBarEntries() {
        BarEntry barEntry1 = new BarEntry(0f, 30f);
        BarEntry barEntry2 = new BarEntry(1f, 40f);
        BarEntry barEntry3 = new BarEntry(2f, 50f);
        BarEntry barEntry4 = new BarEntry(3f, 60f);
        BarEntry barEntry5 = new BarEntry(4f, 70f);

        mBarEntries = new ArrayList<>();
        mBarEntries.add(barEntry1);
        mBarEntries.add(barEntry2);
        mBarEntries.add(barEntry3);
        mBarEntries.add(barEntry4);
        mBarEntries.add(barEntry5);
    }

    private void initBarData() {
        mBarDataSet = new BarDataSet(mBarEntries,"sleep");
        mBarData = new BarData(mBarDataSet);

        // mBarDataSet.setColors(colors); 给柱状图设置颜色

        initX(mBarChart);
        initY(mBarChart);

        Description desc = new Description();
        desc.setText("");
        mBarChart.setDescription(desc);
        mBarChart.setData(mBarData);
        mBarChart.invalidate();
    }

    private void initX(BarChart barChart) {
        final String[] weeks = {"周一","周二","周三","周四","周五"};

        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return weeks[(int)value];
            }
        });
        barChart.getLegend().setEnabled(false);
        xAxis.setLabelCount(weeks.length,false);
    }

    private void initY(BarChart barChart) {
        barChart.getAxisLeft().setDrawZeroLine(true);
        //去掉左侧Y轴刻度
        barChart.getAxisLeft().setDrawLabels(false);
        //去掉左侧Y轴
        barChart.getAxisLeft().setDrawAxisLine(false);
        //去掉中间竖线
        barChart.getXAxis().setDrawGridLines(false);
        //去掉中间横线
        barChart.getAxisLeft().setDrawGridLines(false);
    }


}![![33.png](https://img.haomeiwen.com/i9134822/edc6c466d1e36709.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](https://img.haomeiwen.com/i9134822/345405d28cee41e0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

上一篇下一篇

猜你喜欢

热点阅读