FreeRadioGroup is an Android library that allows grouping radio buttons without constraining them into a Linear Layout fashion, you can place the buttons anywhere you like.
To add FreeRadioGroup to your project add the following gradle dependency:
implementation 'br.com.mauker:freeradiogroup:1.0.1'Also make sure to have jcenter() in your gradle repositories.
To use FreeRadioGroup add the following code in the same XML layout as your Radio Buttons:
<br.com.mauker.freeradiogroup.FreeRadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:referenced_ids="radioButton,radioButton2,radioButton3"
app:checkedRadioButton="@id/radioButton2"
tools:ignore="MissingConstraints" />- The first and most important attribute is
app:referenced_ids. Use it to add radio buttons to this group by adding their IDs; - The
app:checkedRadioButtonattribute will define which radio button from this group should be checked by default; - As of
V_1.0.0if you're addingFreeRadioGroupinside a constraint layout, it's necessary to add thetools:ignore="MissingConstraints"to safely ignore the missing constraints error message.
Note: Since FreeRadioGroup has no width or height, you can use either wrap_content or 0dp.
To use FreeRadioGroup inside your code, simply use findViewById() to get its reference.
val group: FreeRadioGroup = findViewById(R.id.radioGroup)You can either check an individual radio button from a group or clear the selection using the following methods:
group.check(radioButtonId: Int)to check a the radio button from this group;group.clearCheck()to clear the current selection.
You can get the selected radio button by using the group.getCheckedRadioButtonId() method. It'll return the radio button ID or View.NO_ID if there's no selection.
It's also possible to listen for changes in selection by using the OnCheckedChangeListener interface.
group.setOnCheckedChangeListener(object: OnCheckedChangeListener {
override fun onCheckedChanged(group: FreeRadioGroup, checkedId: Int) {
// Do something with the selection
}
})