Android 数据绑定(bind)支持最酷的功能之一是它还可以为带有 ID 集的 View 生成字段。这整理了代码库,因为不需要字段或 findViewById()
调用。
但问题是绑定(bind)实例只能通过倾向于安排绑定(bind)的 bind()
调用来检索。当异步接收数据并且通常会抛出 NullPointerException
时,这是很糟糕的。
是否可以在不进行实际数据绑定(bind)过程的情况下检索带有 View 字段的绑定(bind)实例?
堆栈跟踪:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
at com.app.android.databinding.ActivityRestaurantDetailsBinding.executeBindings(ActivityRestaurantDetailsBinding.java:381)
at android.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:350)
at android.databinding.ViewDataBinding$6.run(ViewDataBinding.java:167)
at android.databinding.ViewDataBinding$5.onViewAttachedToWindow(ViewDataBinding.java:137)
at android.view.View.dispatchAttachedToWindow(View.java:14525)
最佳答案
这似乎没有意义,数据绑定(bind)将忽略空变量,因此不应抛出空指针,我认为这是它最受推崇的功能之一。如果您需要在异步调用等之后修改变量,您可以使用 dataBinding.executePendingBindings()
来自 the docs
The generated binding class will have a setter and getter for each of the described variables. The variables will take the default Java values until the setter is called — null for reference types, 0 for int, false for boolean, etc.
和
Generated data binding code automatically checks for nulls and avoid null pointer exceptions. For example, in the expression @{user.name}, if user is null, user.name will be assigned its default value (null). If you were referencing user.age, where age is an int, then it would default to 0.
关于Android 惰性数据绑定(bind)可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809743/