How can I modify the TalkBack usage hint for a clickable View on Android?

淺唱寂寞╮ 提交于 2019-11-30 20:52:29

Yes, this is absolutely possible!

Overriding the onInitializeAccessibilityNodeInfo method

If you have a custom View, you can override the onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) method and add an action with the ACTION_CLICK ID, to override the label:

@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
    super.onInitializeAccessibilityNodeInfo(info);
    info.addAction(
            new AccessibilityNodeInfo.AccessibilityAction(
                    AccessibilityNodeInfo.ACTION_CLICK,
                    "play video"
            )
    );
}

If that View has a click listener, then by adding this new Action, you'll have overridden the default label so TalkBack will say "Double tap to " instead.

This is only available on API 21 - what if you wanted something that worked on a lower API version or wanted to set a custom usage hint on a non-custom View? You can use ViewCompat and AccessibilityDelegateCompat!

Using an AccessibilityDelegate instead

It's very similar - you can override the equivalent method in a custom AccessibilityDelegate that you extend:

public static class PlayVideoAccessibilityDelegate extends AccessibilityDelegateCompat {

    @Override
    public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
        super.onInitializeAccessibilityNodeInfo(host, info);
        info.addAction(
                new AccessibilityNodeInfoCompat.AccessibilityActionCompat(
                        AccessibilityNodeInfoCompat.ACTION_CLICK,
                        "play video"
                )
        );
    }
}

then to use it, you set the delegate with ViewCompat:

ViewCompat.setAccessibilityDelegate(playButton, new PlayVideoAccessibilityDelegate());

Using accessibilitools

Novoda has a utility library to help with accessibility on Android. This includes some tools to help set usage hints:

UsageHintsAccessibilityDelegate delegate = new UsageHintsAccessibilityDelegate(resources);  
delegate.setClickLabel("play video");

ViewCompat.setAccesibilityDelegate(playButton, delegate);

I wrote a blogpost which is an overview of accessibilitools (I am also a contributor to the library).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!