Skip to content

Instantly share code, notes, and snippets.

@renatoi
Created January 20, 2017 04:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoi/c496c825445c555ba8e5f1cbe444d531 to your computer and use it in GitHub Desktop.
Save renatoi/c496c825445c555ba8e5f1cbe444d531 to your computer and use it in GitHub Desktop.
Using `setLabeledBy` on Android for RadioButton

Layout

<!-- label -->
<TextView
    android:id="@+id/choice_controls_radio_label"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/choice_controls_question"/>

<!-- radio buttons -->
<RadioGroup
    android:id="@+id/choice_controls_radio_group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <RadioButton
        android:id="@+id/choice_controls_radio_button_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="@dimen/min_touch_height"
        android:background="@drawable/focusable"
        android:text="@string/choice_controls_option_1"/>
    <RadioButton
        android:id="@+id/choice_controls_radio_button_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="@dimen/min_touch_height"
        android:background="@drawable/focusable"
        android:text="@string/choice_controls_option_2"/>
</RadioGroup>

Activity/Fragment

// radio buttons
final TextView radioLabel = (TextView) findViewById(R.id.choice_controls_radio_label);
final RadioGroup radioGroup = (RadioGroup) findViewById(R.id.choice_controls_radio_group);

int childCount = radioGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
    View v = radioGroup.getChildAt(i);
    if (v instanceof RadioButton) {
        ViewCompat.setAccessibilityDelegate(v, new AccessibilityDelegateCompat() {
            @Override
            public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
                super.onInitializeAccessibilityNodeInfo(host, info);
                info.setLabeledBy(radioLabel);
            }
        });
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment