androidkotlinandroid-preferencespreferencescreenswitchpreference

How to give contentDescription to SwitchPreference for Accessibilty/Talkback?


I have a Preference screen having multiple SwitchPreferences. I need to give custom contentDescription to each switch for accessibility. There is no property as contentDescription for SwitchPreference. Can Anyone help me in how to give custom description to switchPreferences for Accessibilty/Talkback?


Solution

  • Preferences aren't views. You can't add contentDescription to preferences directly. You need to create a custom preference extending from SwitchPreference and add accessibility information to the switch view in onBindViewHolder.

    public class SwitchPreferenceAccessibility extends SwitchPreference {
    
      @Override
      public void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
        
        View switchView = holder.findViewById(R.id.switchWidget);
        switchView.setContentDescription(getString(R.string.accessibility_information));
      }
    }
    

    or you can use declare-styleable attributes, it would be more convenient.

    public class SwitchPreferenceAccessibility extends SwitchPreference {
    
      public SwitchPreferenceAccessibility(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    
        mContentDescription = TypedArrayUtils.getText(a, R.styleable.SwitchPreferenceAccessibility_content_description, "");
      }
    
      @Override
      public void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
        
        View switchView = holder.findViewById(R.id.switchWidget);
        switchView.setContentDescription(mContentDescription);
      }
    }
    
    <SwitchPreferenceAccessibility
      app:key="key"
      app:title="title"
      app:content_description="@string/accessibility_information" />