I've created a custom setter that sets the text of an enum into an editText:
public enum Gender {
MALE, FEMALE}
XML:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:holder="@={user.gender}" />
Adapter:
@BindingAdapter ("custom:holder")
public static void setHolder(EditText editText, Gender gender) {
editText.setText(gender.toString());
}
From code:
binder= DataBindingUtil.bind(getView());
binder.setUser(user);
How can I specify a getter that returns a Gender
object?
I tried the following code but it doesn't seem to be the right way.
@BindingAdapter ("custom:holder")
public static Gender getHolder(EditText editText) {
return Gender.valueOf(editText.getText().toString());
}
What I want to achieve is that when I call binder.getUser()
, the Gender will be automatically filled.
Is it possible to do that?
Instead of using EditText
for enum value, I suggest to use Spinner
with implementations of @BindingAdapter
and @InverseBindingAdapter
for bidirection binding.
Your dto:
public class User {
private Gender _gender;
public Gender getGender() { return _gender; }
public void setGender(Gender gender) { _gender = gender; }
}
public enum Gender {MALE, FEMALE}
Implementation of @BindingAdapter
for Spinner
:
@BindingAdapter (value = {"custom:holder", "custom:holderAttrChanged"}, requireAll = false)
public static void setHolder(Spinner spinner, Gender gender, final InverseBindingListener listener) {
// setup spinner content
spinner.setAdapter(new ArrayAdapter<>(spinner.getContext(), R.layout.gender_spinner_item, Gender.values()));
// setup listener of notifications to @InverseBindingAdapter
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
listener.onChange();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
listener.onChange();
}
});
}
where gender_spinner_item - it's can be layout with one TextView
.
Implementation of @InverseBindingAdapter
:
@InverseBindingAdapter(attribute = "custom:holder", event = "custom:holderAttrChanged")
public static Gender getHolder(Spinner spinner) {
return (Gender) spinner.getSelectedItem();
}
Layout example:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto">
<data>
<variable name="user" type="com.example.User"/>
</data>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:holder="@={user.gender}" />
</layout>
Binding instance of User
:
binder= DataBindingUtil.bind(getView());
binder.setUser(user);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With