我已经创建了一个自定义setter,它将枚举文本设置为editText:
public enum Gender {
MALE, FEMALE}
XML:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:holder="@={user.gender}" />
适配器:
@BindingAdapter ("custom:holder")
public static void setHolder(EditText editText, Gender gender) {
editText.setText(gender.toString());
}
来自代码:
binder= DataBindingUtil.bind(getView());
binder.setUser(user);
如何指定返回Gender
对象的getter?
我尝试了以下代码,但似乎不是正确的方法。
@BindingAdapter ("custom:holder")
public static Gender getHolder(EditText editText) {
return Gender.valueOf(editText.getText().toString());
}
我想要实现的是,当我致电binder.getUser()
时,性别将自动填充。
有可能吗?
答案 0 :(得分:4)
我建议不要将EditText
用于枚举值,而是将Spinner
与@BindingAdapter
和@InverseBindingAdapter
的实现一起用于双向绑定。
你的dto:
public class User {
private Gender _gender;
public Gender getGender() { return _gender; }
public void setGender(Gender gender) { _gender = gender; }
}
public enum Gender {MALE, FEMALE}
@BindingAdapter
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();
}
});
}
其中 gender_spinner_item - 它可以是一个TextView
的布局。
@InverseBindingAdapter
的实施:
@InverseBindingAdapter(attribute = "custom:holder", event = "custom:holderAttrChanged")
public static Gender getHolder(Spinner spinner) {
return (Gender) spinner.getSelectedItem();
}
布局示例:
<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>
User
的绑定实例:
binder= DataBindingUtil.bind(getView());
binder.setUser(user);