8

I have a custom view that I want to have colored text. But when the high contrast option is enabled canvas ignores all paint's color settings and draws text as black and white (drawText overloads)

It is somewhat possible to detect if this option is enabled(via reflection, etc). Is there a way to ignore that for some views?

PS I know about the switch in settings, that's not a solution.

naixx
  • 1,176
  • 11
  • 17
  • I have the exact same question. I don't want text in canvas affected by this setting. This is happening only on Android 9.0+. On Android 8 canvas text is not affected. – Wesley May 07 '19 at 09:51
  • same question. Have you got any solution ? – Bhaven Shah Dec 18 '20 at 11:44

2 Answers2

4

My workaround looks something like this:

public void drawTextWithoutHighContrastEffects(Canvas canvas, String text, float x, float y, Paint paint)
{
    if (isHighContrastTextEnabled)
    {
        Path path = new Path();
        paint.getTextPath(text, 0, text.length(), x, y, path);
        canvas.drawPath(path, paint);
    } else {
        canvas.drawText(text, x, y, paint);
    }
}

Please note that this is a simplified solution, e.g. path instance should not be recreated for each draw operation, create once and then reuse it. Also paint object should be set up correctly with FILL style in order to make the text drawn using drawPath look the same as drawn by drawText.

The value of isHighContrastTextEnabled flag comes from here: Detect if 'High contrast' is enabled in Android accessibility settings

mlebedy
  • 106
  • 6
0

to force prevent view from adapting to accessibility settings you can set in XML

android:importantForAccessibility="no"

or you can set in code

view.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);

to detect if user have High Contrast Text option enabled you can check this link (Detect if 'High contrast' is enabled in Android accessibility settings)

  • Didn't work for me on OnePlus 5. Tried both IMPORTANT_FOR_ACCESSIBILITY_NO and IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS on the view or its parent. Tried both programmatic and static approaches. – A. Kazarovets Jan 20 '20 at 08:39
  • 2
    As they say in the docs: "Note: While not recommended, an accessibility service may decide to ignore this attribute and operate on all views in the view tree." https://developer.android.com/reference/android/view/View.html#attr_android:importantForAccessibility – A. Kazarovets Jan 20 '20 at 08:41