BindingAdapter自定义getter 2路数据绑定

时间:2017-01-24 11:49:58

标签: android android-databinding

我已经创建了一个自定义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()时,性别将自动填充。 有可能吗?

1 个答案:

答案 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);