Android 数据绑定:BindingAdapter 与 InverseBindingAdapter

Android databinding: BindingAdapter vs InverseBindingAdapter

两者有什么区别?

什么时候应该使用其中之一?

当我定义一个 BindingAdapter 时,我必须创建一个反函数吗?

引用我自己,来自 The Busy Coder's Guide to Android Development:

Two-way binding works well in cases where the way you store the data in the models lines up well with the getters and setters of the associated widget. A boolean field in the model works well with the checked property of a CompoundButton like a Switch, as CompoundButton has an isChecked() method returning a boolean and a setChecked() accepting a boolean.

A BindingAdapter allows you to create other mappings between data types and properties, but only for the classic model->view binding. To accomplish the same thing in the reverse direction, you wind up creating an InverseBindingAdapter. As the name suggests, this serves the same basic role as a BindingAdapter, but in the inverse direction, taking data from the widget and preparing it for the model using custom code. Here, the "preparing it for the model" means converting it into a suitable data type for a setter, Observable field, etc. for your model.

This is fairly unusual.

The example used in some places is "what if I want to tie a float to an EditText?". The InverseBindingAdapter would look something like this:

@InverseBindingAdapter(attribute = "android:text")
public static float getFloat(EditText et) {
  try {
    return(Float.parseFloat(et.getText().toString()));
  }
  catch (NumberFormatException e) {
    return(0.0f); // because, um, what else can we do?
  }
}

The problem is if the user types in something that is not a valid floating-point number, like snicklefritz. parseFloat() will fail with a NumberFormatException. You should let the user know that their data entry was invalid. However, two-way data binding does not support this, with a default value (e.g., 0.0f) being handed to the model instead.

所以,回答你的问题:

What is the difference between the two?

BindingAdapter 有助于填充属性,其中数据类型和 View setter 不是数据绑定知道如何自行处理的东西。

InverseBindingAdapter 有助于在双向绑定中填充视图模型,其中数据类型和 View 吸气剂不是数据绑定知道如何自行处理的东西。

When should use one or the other? When I define a BindingAdapter do I have to create an inverse?

当您想要的数据类型(例如 float)不是数据绑定必须知道如何填充到小部件 属性(例如,android:textEditText) 上,但你还是想绑定它。

如果你这样做,你想做双向绑定,用户在 UI 中的更改会自动更新你的视图模型,很可能你将需要一个匹配的 InverseBindingAdapter 来从 属性(例如 EditText 的文本)转换为所需的数据类型(例如 float)。