首页 > 解决方案 > 自定义的 Android GraphView x 轴日期标签未按 setNumHorizo​​ntalValues() 显示

问题描述

我尝试在 graphview 图表的 x 轴上显示格式简洁的日期/时间。根据API 代码示例,在该轴上使用日期格式化程序时,我将 HumanRounding 设置为 false。我还将 NumHorizo​​ntalLabels 设置为 3,以便在两个方向都显示合理。

这导致例如以下情况,其中日期标签显示为黑色形状,并且 LineChart 背景不同。我推测黑色形状是我所有日期数据点相互覆盖的结果:

将 HumanRounding 设置为 false

将 HumanRounding 设置为 true (注释掉),我得到标签显示,但不是预期的 3 个均匀分布的标签,而是不可预测地分布和/或不等于 3,有时标签会相互覆盖,有时它们是挤在左边...

真人四舍五入

x 轴上的日期数据点的数量可能会根据用户选择的历史记录数量而有所不同。请注意,这可能从 60 到数千分钟不等。

这是接收数据并绘制图表的代码。请注意,从 wxList 元素检索到的 unixdate 在它们在这里使用时已经转换为 Java 日期(乘以 1000)(当它们以合理的方式显示时,x 轴的时间部分实际上是正确的)分布式方式):

       protected void onPostExecute(List<WxData> wxList) {

            // We will display MM/dd HH:mm on the x-axes on all graphs...
            SimpleDateFormat shortDateTime = new SimpleDateFormat("MM/dd HH:mm");
            shortDateTime.setTimeZone(TimeZone.getTimeZone("America/Toronto"));
            DateAsXAxisLabelFormatter xAxisFormat = new DateAsXAxisLabelFormatter(parentContext, shortDateTime);

            if (wxList == null || wxList.isEmpty()) {
                makeText(parentContext,
                        "Could not retrieve data from server",
                        Toast.LENGTH_LONG).show();
            } else {

                // Temperature Celcius
                GraphView tempGraph = findViewById(R.id.temp_graph);
                tempGraph.removeAllSeries();
                tempGraph.setTitle(parentContext.getString(R.string.temp_graph_label));
                DataPoint[] tempCArray = new DataPoint[wxList.size()];
                for (int i = 0; i < wxList.size(); i++) {
                    tempCArray[i] = new DataPoint(wxList.get(i).getUnixtime(), wxList.get(i).getTempC().doubleValue());
                }
                LineGraphSeries<DataPoint> tempCSeries = new LineGraphSeries<>(tempCArray);
                tempGraph.addSeries(tempCSeries);
                tempGraph.getGridLabelRenderer().invalidate(false, false);
                tempGraph.getGridLabelRenderer().setLabelFormatter(xAxisFormat);
                tempGraph.getGridLabelRenderer().setNumHorizontalLabels(3);
                tempGraph.getViewport().setMinX(wxList.get(0).getUnixtime());
                tempGraph.getViewport().setMaxX(wxList.get(wxList.size() - 1).getUnixtime());
                tempGraph.getViewport().setXAxisBoundsManual(true);
                // Code below seems buggy - with humanRounding, X-axis turns black
//                tempGraph.getGridLabelRenderer().setHumanRounding(false);
...

我尝试了很多变体,但我无法让图表始终如一地显示 3 个日期时间均匀分布,对于两个方向,对于不同的样本大小。任何帮助表示赞赏。

标签: android-graphview

解决方案


推荐阅读