如何在辅助功能打开时更改/覆盖复选框内容说明值



我的活动中有一个复选框,并提供了android:contentDescription="selected"。同样在java类中提供如下。

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        checkbox.setContentDescription(b ? "Selected" : "Not Selected");
    }
});

当我打开对讲并选中复选框时,它会显示"选中/未选中"而不是"已选择/未选择"。

它采用操作系统的默认值(因制造商和操作系统版本而异),但不提供值。有什么办法,我们可以解决这个问题吗?

所以我不久前遇到了这个问题,并发现了一个相当笨拙的解决方法。像这样创建和使用 CheckBox 的子类并替换字符串:

public class CustomCheckBox extends CheckBox {
    // constructors...
    @Override
    public CharSequence getAccessibilityClassName() {
        // override to disable the "checkbox" readout
        return CustomCheckBox.class.getSimpleName();
    }
    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        // by setting checkable to false the default checked/unchecked readouts are disabled
        info.setCheckable(false);
        // ...and then you can set whatever you want as a text
        info.setText(getStateDescription());
    }
    @Override
    public void setChecked(boolean checked) {
        if (checked == isChecked()) return;
        super.setChecked(checked);
        // since we've disabled the checked/unchecked readouts
        // we are forced to manually announce changes to the state
        announceForAccessibility(getStateDescription());
    }
    private String getStateDescription() {
        if (isChecked()) {
            return "Custom checked description";
        } else {
            return "Custom unchecked description";
        }
    }
}

另外,我应该首先说我没有尝试过下面提到的东西,但似乎Android R(API 30)通过向源文档添加setStateDescription(CharSequence)来添加来添加CompoundButton方法来覆盖它

/**
 * This function is called when an instance or subclass sets the state description. Once this
 * is called and the argument is not null, the app developer will be responsible for updating
 * state description when checked state changes and we will not set state description
 * in {@link #setChecked}. App developers can restore the default behavior by setting the
 * argument to null. If {@link #setChecked} is called first and then setStateDescription is
 * called, two state change events will be merged by event throttling and we can still get
 * the correct state description.
 *
 * @param stateDescription The state description.
 */
@Override
public void setStateDescription(@Nullable CharSequence stateDescription) {
    mCustomStateDescription = stateDescription;
    if (stateDescription == null) {
        setDefaultStateDescritption();
    } else {
        super.setStateDescription(stateDescription);
    }
}

最新更新