Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically check an Android radio button with ripple animation?

tl;dr: When the user clicks an unrelated text view, I want a radio button to be selected with a ripple animation. performClick doesn't do this. What should I be doing instead?

I have a radio button with both a label and a longer description.

enter image description here

The general structure of my layout is this:

<RadioGroup>

  <RadioButton
      id="@+id/officialBusinessRadio"
      text="Official business" />

  <TextView
      id="@+id/officialBusinessCaption"
      text="This operates under a ..." />

  <!-- ... -->

</RadioGroup>

I've added an OnClickListener to the text view so that tapping on the caption selects the radio button:

officialBusinessCaption.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    officialBusinessRadio.performClick();
  }
});

When I tap on the radio button itself or on its own text ("Official Business"), the radio button animates to selected and a ripple ink effect occurs. When I top on the caption text (and performClick is called), the radio button still animates to selected, but no ripple occurs.

Is there a more correct way to get this effect? That is, is there a better way to forward a click on the caption text view to the radio button? If not, is there a straightforward way to trigger the ripple effect on the radio button programmatically?

I would prefer against setting all the text using a string resource for the following reasons:

  • I intend on styling the label and the caption differently.
  • I want the radio vertically center aligned with the first line of text.
like image 476
Wesley Avatar asked Oct 19 '22 06:10

Wesley


1 Answers

I've hit this problem by population RadioButtons in a RecyclerView. All of them are set to isClickable = false because I override their selection according to another rule, but the way to trigger the selection to true is doing:

Kotlin:

    radioButton.post {
        radioButton.isChecked = true
    }

Java:

    radioButton.post(new Runnable() {
        @Override
        public void run() {
            radioButton.setChecked(true);
        }
    })

before, I was doing setChecked(true) only and it wouldn't work.

like image 80
Rafael Ruiz Muñoz Avatar answered Oct 31 '22 19:10

Rafael Ruiz Muñoz