Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android data binding, Radio Button not updating

I have some RadioButtons and I want them to be checked/unchecked as the model changes, using Data Binding.
I managed to set up an EditText and it is working fine.
Anyway, the RadioButtons behave as the android:checked property wouldn't be there.

<RadioButton 
    android:id="@+id/radio_kitchen"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/kitchen"
    android:checked="@{radiator.room==@string/kitchen?true:false}"
/>
like image 782
Marco Menardi Avatar asked Feb 15 '16 18:02

Marco Menardi


People also ask

How to create custom ID and value for radio button?

You can create custom ids for each radio button and use android:checkedButton of radiogroup to retain checked state of radio button via two way data binding. For value of radio button you can use android:onClick attribute to have specific value according to your business logic

Does edittext work with radiobuttons?

I managed to set up an EditText and it is working fine. Anyway, the RadioButtons behave as the android:checked property wouldn't be there.

What is data binding library in Android?

The Data Binding Library is an Android Jetpack library that allows you to bind UI components in your XML layouts to data sources in your app using a declarative format rather than programmatically, reducing boilerplate code. This codelab has been designed for those with some Android development experience.

How do I convert an existing layout to data binding?

It is a regular layout with a ConstraintLayout as the root element. In order to convert the layout to Data Binding, you need to wrap the root element in a <layout> tag. You'll also have to move the namespace definitions (the attributes that start with xmlns:) to the new root element.


Video Answer


1 Answers

This is what I am currently doing for this:

        <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@{() -> car.setModel(@string/car_model_toyota)}"
        android:checked="@{car.model.equals(@string/car_model_toyota)}"
        android:text="@string/car_model_toyota"/>

It's cheating since I am kind of giving some code logic to the View... but at least I don't have to implement an onchange listener on every single radiogroup and I still get the binding to happen...

Unless someone correct me and gives me a more ethic and professional solution I think I am going to stick with this one.

like image 126
Benjamin Vison Avatar answered Sep 28 '22 23:09

Benjamin Vison