good,
I want that when my application starts, a RadioButton that is inside a RadioGroup is selected.
The dilemma is that in the ViewModel I have a "filter" that is a LiveData, which is observed by the activity. This LiveData is created by the SavedStateHandle class, to preserve the state even if the activity is killed due to lack of resources, so the selected RadioButton must be according to the current value of said filter _currentFilter
. That's why I need to mark the RadioButton at runtime and I can't do it beforehand from the Layout.
This is what I have tried:
private fun setupRadioGroup() {
setupRadioButtonsTag()
setupInitialFilterSelected()
setupRadioGroupListener()
}
private fun setupRadioButtonsTag() {
for (i in 0 until binding.rgTasksFilter.childCount) {
binding.rgTasksFilter.getChildAt(i).tag = TasksFilter.values()[i]
}
}
private fun setupInitialFilterSelected() {
val position = viewModel.currentFilter.value?.ordinal ?: 0
binding.rgTasksFilter.getChildAt(position).isSelected = true
}
private fun setupRadioGroupListener() {
binding.rgTasksFilter.setOnCheckedChangeListener { group, checkedId ->
for(i in group) {
if(i.id == checkedId) {
val filter = i.tag as TasksFilter
viewModel.changeFilter(filter)
}
}
}
}
private val _currentFilter = handle.getLiveData(FILTER_SELECTED, TasksFilter.ALL)
val currentFilter: LiveData<TasksFilter>
get() = _currentFilter
enum class TasksFilter { ALL, PENDING, COMPLETED }
<RadioGroup
android:id="@+id/rgTasksFilter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="@dimen/margin_2x">
<RadioButton
android:id="@+id/rbTaskAllOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/margin"
android:text="@string/tasks_lblFilterAll" />
<RadioButton
android:id="@+id/rbTaskPendingOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/margin"
android:text="@string/tasks_lblFilterPending" />
<RadioButton
android:id="@+id/rbTaskCompletedOption"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tasks_lblFilterCompleted" />
</RadioGroup>
The filter appears to be selected, but "graphically" is not checked.
Thanks.
Have you tried the checked property?
View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled on a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have a corresponding ID in the layout.
In most cases, view binding replaces findViewById.
How does it work?
In the "build.gradle" of your app:
In your Activity:
And the last thing I told you is that there is another way to do it, which is by adding the variable to the layout:
I hope I can help you with this explanation. Greetings.