启用辅助功能后,如何更改/覆盖复选框内容描述值?

时间:2019-01-12 15:37:58

标签: android accessibility

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

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

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

它采用的是OS的默认值(不同制造商和OS版本的不同),但未提供值。有什么办法可以解决这个问题?

1 个答案:

答案 0 :(得分:0)

所以我前一段时间遇到了这个问题,发现了一个相当棘手的解决方法。 这样创建并使用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) {{3中添加CompoundButton }} Source

/**
 * 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);
    }
}