当使用MPAndroidChart时,可以动态刷新图表,但当数据量大于一定程度时,界面会卡住,所以需要定期清除数据点。
- /**
- * 动态添加数据(一条折线图)
- *
- * @param number
- */
- public void addEntry(float number) {
- if (lineDataSet.getEntryCount() == 0) {
- lineData.addDataSet(lineDataSet);
- }
-
- if (timeList.size() == 512) {
- timeList.remove(0); // 移除最旧的数据
- }
- timeList.add(df.format(System.currentTimeMillis()));
-
- Entry entry = new Entry(lineDataSet.getEntryCount(), number);
- lineData.addEntry(entry, 0);
- // 处理完数据后再更新UI
- updateChart();
-
- if(lineDataSet.getEntryCount() == 512) {
- lineDataSet.removeFirst();
- // change Indexes - move to beginning by 1
- for (Entry e : lineDataSet.getValues())
- e.setX(e.getX() - 1);
- }
- }
- /**
- * 动态添加数据(多条折线图)
- *
- * @param numbers
- */
- public void addEntry(List
numbers) { - if (lineDataSets.get(0).getEntryCount() == 0) {
- lineData = new LineData(lineDataSets);
- lineChart.setData(lineData);
- }
- if (timeList.size() == 16) {
- timeList.remove(0);
- }
- timeList.add(df.format(System.currentTimeMillis()));
- for (int i = 0; i < numbers.size(); i++) {
- Entry entry = new Entry(lineDataSet.getEntryCount(), numbers.get(i));
- lineData.addEntry(entry, i);
- lineData.notifyDataChanged();
- lineChart.notifyDataSetChanged();
- lineChart.setVisibleXRangeMaximum(6);
- lineChart.moveViewToX(lineData.getEntryCount() - 1);
- }
- if (lineData.getEntryCount() == 48) {
- lineData.removeEntry(0,0);
- lineData.removeEntry(0,1);
- lineData.removeEntry(0,2);
- for (ILineDataSet dataSet : lineData.getDataSets()) {
- for (int i = 0; i < dataSet.getEntryCount(); i++) {
- Entry entry = dataSet.getEntryForIndex(i);
- entry.setX(entry.getX() - 1);
- }
- }
- lineData.notifyDataChanged();
- }
- }