Hi, I want to color the axis label by its value,
eg. value< 0 -> show with red color
value = 0 -> show grey color
value > 0 -> show green color
similar to this question, but in android platform, it seems the LabelProvider has function related to the value(string) formatting only. Is there any ways to styling the label? Thanks!
- may lym asked 7 years ago
- You must login to post comments
Hi May Lym,
Yes, it’s possible by returning SpannableString with color from LabelProvider.
You’ll need to implement custom LabelFormatter which uses default implementation for formatting and then wraps it into SpannableString with desired color:
class CustomLabelFormatter implements ILabelFormatter<NumericAxis> {
private final NumericLabelFormatter defaultFormatter = new NumericLabelFormatter();
@Override
public void update(NumericAxis axis) {
defaultFormatter.update(axis);
}
@Override
public CharSequence formatLabel(Comparable dataValue) {
return formatLabelInternal(dataValue, defaultFormatter.formatLabel(dataValue));
}
private static CharSequence formatLabelInternal(Comparable dataValue, CharSequence formattedValue) {
final double doubleValue = ComparableUtil.toDouble(dataValue);
if(doubleValue < 0d) {
return formatLabelWithColor(formattedValue, Color.RED);
} else if(doubleValue > 0d) {
return formatLabelWithColor(formattedValue, Color.GREEN);
} else
return formatLabelWithColor(formattedValue, Color.GRAY);
}
private static CharSequence formatLabelWithColor(CharSequence label, int color) {
final SpannableString coloredString = new SpannableString(label);
coloredString.setSpan(new ForegroundColorSpan(color), 0, label.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return coloredString;
}
@Override
public CharSequence formatCursorLabel(Comparable dataValue) {
return formatLabelInternal(dataValue, defaultFormatter.formatCursorLabel(dataValue));
}
}
Then use this custom LabelFormatter for your axis:
xAxis.setLabelProvider(new NumericLabelProvider(new CustomLabelFormatter()));
Hope this will help you!
Best regards,
Yura
- Yura Khariton answered 7 years ago
- You must login to post comments
Please login first to submit.