2

我有一个 TimeChart,初始日期格式是“MM-dd-yyyy”,如下所示。

mChart = ChartFactory.getTimeChartView(getActivity(), mDataset, mRenderer,"MM-dd-yyyy");

现在我希望格式为“MM-dd-yyyy”中的“MMM-yy”,而无需再次调用“ChartFactory.getTimeChartView”方法并再次创建整个图表视图。

这可能吗?

4

2 回答 2

1

您不能直接这样做,但还有其他一些解决方案,例如自定义标签。

于 2013-09-09T19:10:37.093 回答
1

我有一个更改格式的解决方案。

private static final int NUM_LABELS = 5;
private XYMultipleSeriesRenderer mMultiRenderer;
private XYMultipleSeriesDataset mDataset;
private GraphicalView mChart;

private void applyCustomXLabels(String format, boolean useFormat) {
    // Get the min and max (dates) in the current 'window'
    double min = mMultiRenderer.getXAxisMin();
    double max = mMultiRenderer.getXAxisMax();

    // Remove any custom x labels
    mMultiRenderer.clearXTextLabels();

    // If not using the custom format, allow the labels to be auto generated
    // using the default label generator
    if (!useFormat) {
        // Set the number of auto-generated labels
        mMultiRenderer.setXLabels(NUM_LABELS);
    } else {
        // Get evenly spaced label locations between min and max
        List<Double> labelLocations = MathHelper.getLabels(min, max, NUM_LABELS);
        // Go through each location
        for(Double d : labelLocations) {
            // Add a custom x label using the double as the location and format it to a date
            mMultiRenderer.addXTextLabel(d, new SimpleDateFormat(format).format(new Date(Math.round(d))));
        }
        // Remove the auto-generated x labels
        mMultiRenderer.setXLabels(0);
    }
    // May or may not be needed
    mChart.repaint();
}

现在,请记住,一旦调用了它,一旦您缩放或平移,它将毫无用处。为了保持有用,请执行以下操作:

private static final String NEW_LABEL_FORMAT = "MMM-yy";

private class ChartZoomListener implements ZoomListener {
    @Override
    public void zoomApplied(ZoomEvent zoomEvent) {
        applyCustomXLabels(NEW_LABEL_FORMAT, true);
    }
    @Override
    public void zoomReset() { }
}

private class ChartPanListener implements PanListener {
    @Override
    public void panApplied() {
        applyCustomXLabels(NEW_LABEL_FORMAT, true);
    }
}


private void setupChart(){
    // Getting a reference to LinearLayout
    LinearLayout chartContainer = (LinearLayout) getView().findViewById(R.id.trends_chart_container);
    mChart = ChartFactory.getTimeChartView(getActivity().getBaseContext(), mDataset, mMultiRenderer, "MM-dd-yyyy");
    chartContainer.addView(mChart);
    mChart.addZoomListener(new ChartZoomListener(), true, true);
    mChart.addPanListener(new ChartPanListener());
}
于 2015-05-21T17:16:14.230 回答