MPAndroidChart 的 ValueFormatter 重复了两次值

ValueFormatter at MPAndroidChart repeated twice values

我想通过 MPAndroidChart:v3.0.3 创建图表,所以我已经将它的库实现到我的 gradle 中。 在我的 MainActivity class 中初始化图表后进行练习,如下所示:

barChart = findViewById(R.id.chart_report);
barChart.setDrawBarShadow(false);
barChart.setDrawValueAboveBar(true);
barChart.setPinchZoom(false);
barChart.setDrawGridBackground(true);
barChart.setFitBars(true);

我有这样设置图表:

ArrayList<BarEntry> barEntries = new ArrayList<>();
barEntries.add(new BarEntry(1, 40f));
barEntries.add(new BarEntry(2, 20f));
barEntries.add(new BarEntry(3, 35f));
barEntries.add(new BarEntry(4, 15f));

BarDataSet barDataSet = new BarDataSet(barEntries, "DataSet1");
barDataSet.setColors(ColorTemplate.COLORFUL_COLORS);

BarData data = new BarData(barDataSet);
data.setBarWidth(0.3f);

barChart.setData(data);

现在一切正常,但我想更改它 XAxis 所以为了我创建了一个 class 并实现了 IAxisValueFormatter 接口,如下所示:

public class ChartAXisValueFormatter implements IAxisValueFormatter {
    private String[] mValues;

    public ChartAXisValueFormatter(String[] values) {
        mValues = values;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {

        int val = (int) (value);
        String label = "";
        if (val >= 0 && val < mValues.length) {
            label = mValues[val];
        } else {
            label = "";
        }
        return label;
    }
}

并像这样使用 class:

String[] report = new String[]{"A", "B", "C", "D"};
XAxis xAxis = barChart.getXAxis();
xAxis.setValueFormatter(new ChartAXisValueFormatter(report));
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

但如您所见,C 重复了两次!!!为了避免这个问题,我必须在 getFormattedValue 中使用什么逻辑?

发生这种情况是因为您必须为 xAxis 指定准确的标签数:

xAxis.setLabelCount(barEntries.size());

另见:

还有一点更正,索引应该是:

int val = (int) (value) -1;