How to set content description of a switch or toggle button in Android Studio?

Viewed 1369

I would like to make my app accessible with Tlkback, but I don't know how could I set different content descriptions for both states of a switch or toggle button.

Do you have any suggestions?

2 Answers

You can set content description programmatically like this.

toggleButton.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick( View v ) {
            if( toggleButton.isChecked() ) {
                toggleButton.setContentDescription( "Selected" );
            } else {
                toggleButton.setContentDescription( "Unselected" );
            }
        }
    } );

Use AccessibilityNodeInfo's setChecked and setCheckable. https://developer.android.com/reference/android/view/accessibility/AccessibilityNodeInfo#setCheckable(boolean)

class MyAccessibilityDelegate extends View.AccessibilityDelegate {

  MyButton button;

  public constructor (MyButton button) {
    this.button = button;
  }

  @Override
  public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
    super.onInitializeAccessibilityNodeInfo(host, info);
    
    info.setCheckable(true);
    info.setChecked(button.getChecked());

And then add delegate to your view/layout/etc.

class MyButton extends View {
...
  public constructor() {
    setAccessibilityDelegate(new MyAccessibilityDelegate(this);
  }
...
}

Explanation: All accessibility services should be using AccessibilityNodeInfo to determine what is spoken out loud. setCheckable makes the service aware that the View has modifiable states, while setChecked actually changes the "checked/not checked" callout.

Related