我有一个小问题 . 我正在尝试制作BarCharts的列表视图,其中xAxis表示类别,yAxis - 成本 .
这是我的数据 . 条目
entries.add(new BarEntry(xAxis, cost, categoryName));
xAxis只是图表中的一个位置,我把类别名称作为第三个参数 . 然后我把它放在BarData的数组列表中
ArrayList<BarData> months = new ArrayList<>();
BarDataSet set = new BarDataSet(entries, monthName);
ArrayList<IBarDataSet> dataSets = new ArrayList<>();
dataSets.add(set);
BarData barData = new BarData(dataSets);
months.add(barData);
然后在适配器中设置值formatter
BarData data = getItem(position);
...
xAxis.setValueFormatter(new MyValueFormatter(data.getDataSetByIndex(0)));
在MyValueFormatter中我试图从条目中获取类别名称并将其设置为xAxis值 .
public class MyValueFormatter implements IAxisValueFormatter {
private IBarDataSet mDataSet;
public StatisticByMonthValueFormatter(IBarDataSet data) {
mDataSet = data;
}
@Override
public String getFormattedValue(float value, AxisBase axis) {
return (String) mDataSet.getEntryForIndex((int) value).getData();
}
}
这是炒作,但有时当我滚动列表视图时,我得到了
java.lang.IndexOutOfBoundsException: Invalid index 4, size is 2.
我知道,MyValueFormatter中的getFormattedValue方法中的错误,但我不明白如何解决这个问题,或者如何以正确的方式实现这个?
1 回答
DataSet#getEntryForIndex(int index)
在这里打电话是错误的方法 .
DataSet
中的Entry
存储在后备阵列中,此方法将在后备阵列中的该索引处获取Entry
. 这并不总是对应于该x值的Entry
(图表上的x值) . 因此,IndexOutOfBoundsException
.您可能想要做一些事情:
return (String) mDataSet.getEntryXPos(float value).getData();
有关详细说明,请参阅javadoc for DataSet