How to set the Date Format for CombinedXYChart in

2019-07-16 17:42发布

问题:

I can set the date format in the time chart like this

final GraphicalView view = ChartFactory.getTimeChartView(context, dataset,
                mRenderer, "dd-MMM-yyyy");

but I can't do the same in the case of ComninedXYChart

String[] types = new String[] { TimeChart.TYPE , ScatterChart.TYPE, ScatterChart.TYPE};
final GraphicalView view = 
    ChartFactory.getCombinedXYChartView(context, dataset, mRenderer, types);

image below:

any ideas?

回答1:

In the CombinedXYChart case, you will have to use custom labels:

// disable the default labels
renderer.setXLabels(0);
// add several such labels
renderer.addXTextLabel(x, "label");


回答2:

Actually I have found much better approach. The trick is to use method setXLabelFormat combined with overloaded NumberFormat:

 SimpleDateFormat mDateFormatter = new SimpleDateFormat("d MMM");
 renderer.setXLabelFormat(new NumberFormat() {
        @Override
        public StringBuffer format(double value, StringBuffer buffer, FieldPosition field) {
            return mDateFormatter.format(value, buffer, field);
        }

        @Override
        public StringBuffer format(long value, StringBuffer buffer, FieldPosition field) {
            return mDateFormatter.format(value, buffer, field);
        }

        @Override
        public Number parse(String string, ParsePosition position) {
            return mDateFormatter.parse(string, position).getTime();
        }
    });

Of course it would much bettter if method setXLabelFormat accepted Format (which is base class of all formats) instead of NumberFormat, however i think it is still elegant and quite simple sollution.