MPAndroidChart v3.x.x: upgraded from 2.x.x labels

若如初见. 提交于 2019-11-29 11:25:56
David Rawson

First question

mBarChart.setDescription(); doesn't work anymore

As per this answer here the correct way to set description is now:

    mChart.getDescription().setText("Description of my chart);

Third question

BarData barData = new BarData(ArrayList<String>, ArrayList<IBarDataSet>); doesn't work anymore

There is a different method of adding labels than before. In MPAndroidChart 2.x.x you would pass the xIndex labels as an ArrayList<String> parameter for the constructor of BarData. If you try that in 3.x.x then you will get a message like this:

BarData (com.github.mikephil.charting.interfaces.datasets.IBarDataSet...) in BarData cannot be applied to (java.lang.String[],java.util.ArrayList<com.github.mikephil.charting.interfaces.datasets.IBarDataSet>)

This applies to many popular but outdated tutorials like the Truition tutorial for MPAndroidChart here

Instead, in MPAndroidChart 3.x.x the way to do this is by using a IAxisValueFormatter. This interface has a single method getFormattedValue(float value, AxisBase axis) which you implement to programatically generate your label.

There is an example in the sample project and in the answer here

Altogether, the correct way to add data to a BarChart in MPAndroidChart3.x.x is the following (as per the example in the sample project):

 ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
 dataSets.add(set1);
 BarData data = new BarData(dataSets);
 mChart.setData(data);
 mChart.getXAxis().setValueFormatter(new MyCustomValueFormatter()); // your own class that implements IAxisValueFormatter

Note: if you must use an ArrayList<String> for your labels you can use the convenience class IndexAxisValueFormatter

You consume it like this:

List<String> labels;
//TODO: code to generate labels, then
mChart.getXAxis().setValueFormatter(new IndexAxisValueFormatter(labels));

You will need:

mChart.getXAxis().setGranularity(1);
mChart.getXAxis().setGranularityEnabled(true);

to mimic the behaviour of MPAndroidChart 2.x.x where only whole number xIndices receive labels.

As for your second question, because the label functionality is very finely controlled by the IAxisValueFormatter you won't need the setSpaceBetweenLabels() any more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!