我遇到了PieChart的问题。我每次调用Activity时都会更新Chart,我这样做是为了:
private void setupPieChart() {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
mChart.setLayoutParams(params);
mChart.setUsePercentValues(true);
/**
* Hide the Description and the Legend.
*/
mChart.setDescription("");
mChart.getLegend().setEnabled(false);
/**
* Hole in the middle.
*/
mChart.setDrawHoleEnabled(true);
mChart.setHoleRadius(50);
mChart.setTransparentCircleRadius(55);
mChart.setRotationAngle(0);
mChart.setRotationEnabled(true);
mChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
@Override
public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
switch (e.getXIndex()) {
case 0:
startLearning(e.getXIndex());
break;
case 1:
startLearning(e.getXIndex());
break;
case 2:
startLearning(e.getXIndex());
break;
case 3:
startLearning(e.getXIndex());
break;
case 4:
startLearning(e.getXIndex());
break;
default:
break;
}
}
@Override
public void onNothingSelected() {
System.out.println("onNothingSelected");
}
});
addDataForPieChart();
}
我正在添加数据:
private void addDataForPieChart() {
/**
* Data of the Chart.
*/
float[] value = mCurrentLearnSet.getCountFromLevel();
String[] names = {"First Level", "Second Level", "Third Level", "Forth Level", "Fifth Level"};
/**
* Create needed Entries.
*/
List<Entry> entries = new ArrayList<>();
List<String> strings = new ArrayList<>();
for (int i = 0; i < value.length; i++) {
if (value[i] != 0) {
entries.add(new Entry(value[i], i));
strings.add(names[i]);
}
}
/**
* Create pie data set.
*/
PieDataSet dataSet = new PieDataSet(entries, "Your Progress");
dataSet.setSliceSpace(3);
dataSet.setSelectionShift(5);
/**
* Setup Colors.
*/
dataSet.setColors(ColorTemplate.LIBERTY_COLORS);
/**
* Instantiate pie data object.
*/
PieData data = new PieData(strings, dataSet);
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(13f);
data.setValueTextColor(R.color.primary_text);
/**
* Set the Data to the PieChart.
*/
mChart.setData(data);
/**
* Undo all highlights.
*/
mChart.highlightValues(null);
/**
* Update pie chart.
*/
mChart.notifyDataSetChanged();
mChart.invalidate();
}
我的问题如下:
每次创建时,图表中都有不同数量的切片。 OnChartValueSelectedListener()
不时无法正常工作。切片显示正确,但方法onValueSelected()
从未被调用,因此我无法单击它们。但是没有错误或突出显示。只需调用onNothingSelected()
。
请建议,我该怎么办?
答案 0 :(得分:1)
问题是以下代码段中条目的缺失索引。由于我删除了if语句,代码再次正常工作。
/**
* Create needed Entries.
*/
List<Entry> entries = new ArrayList<>();
List<String> strings = new ArrayList<>();
for (int i = 0; i < value.length; i++) {
if (value[i] != 0) { // <--
entries.add(new Entry(value[i], i));
strings.add(names[i]);
}
}
答案 1 :(得分:-1)
我认为您已经设置了mchart.data.setHighLightEnabled(false),请尝试将其设置为true,届时onValueSelected()将被调用