如何在MPAndroidChart中设置xAxis的字符串值?
作者:互联网
我想制作折线图,但我有问题在xAxis中显示值字符串,我使用Library Github从MPAndroidChart到LineChart.请帮我如何添加字符串值,实际上我想问的问题
private void drawLineChartLine(){
private float[] yDataL = {40, 60, 70, 80};
private String[] xDataL = {"Week 1", "Week 1" , "Week 3" , "Week 4"};
ArrayList<Entry> yEntrys = new ArrayList<>();
final ArrayList<String> xEntrys = new ArrayList<>();
for(int i = 0; i < yDataL.length; i++){
yEntrys.add(new Entry(yDataL[i] ,i));
}
for(int i = 1; i < xDataL.length; i++){
xEntrys.add(xDataL[i]);
}
//create the data set
LineDataSet lineDataset = new LineDataSet(yEntrys, "assa");
XAxis xAxis = lineChart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setDrawGridLines(false);
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return xEntrys.get((int) value);
}
});
LineData lineData = new LineData(lineDataset);
lineChart.setData(lineData);
lineChart.invalidate();
}
我收到了错误
Invalid index 40, size is 6
在代码中
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return xEntrys.get((int) value);
}
});
解决方法:
您正在访问超出范围的ArrayList索引,因为您尝试使用value作为索引.您需要找到值的索引才能返回它.
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
for (int i = 0 ; i < yEntrys.size(); ++i) {
if (yEntrys.get(i).equals(value)) {
return xEntrys.get(i);
}
}
return null;
}
});
标签:mpandroidchart,linechart,android 来源: https://codeday.me/bug/20190823/1699603.html