使用数据绑定膨胀视图

Inflating view using data binding

这是我在 onCreateView 中的代码:

val binding = DataBindingUtil.inflate<SplashFragmentBinding>(
inflater,R.layout.splash_fragment,container,false)

我的问题是,为什么需要添加类型 <SplashFragmentBinding> 并发送 layoutId R.layout.splash_fragment,因为它们几乎相同。如果我的类型是 <SplashFragmentBinding> 则没有其他 layoutId 的可能性。我认为它是冗余的。

如谷歌代码中所见:

public static <T extends ViewDataBinding> T inflate(@NonNull LayoutInflater inflater,
        int layoutId, @Nullable ViewGroup parent, boolean attachToParent) {
    return inflate(inflater, layoutId, parent, attachToParent, sDefaultComponent);
}

why it is requred to add the type and also send the layoutId R.layout.splash_fragment as they practically the same. If my type is there is no other possibility for other layoutId. Its redundancy I think.

你是对的,两者在逻辑上应该是一样的;但你可以同时提供两者的原因;存在编译器无法确定类型的奇怪情况;作为 In documentation:

Sometimes the binding type cannot be known in advance. In such cases, the binding can be created using the DataBindingUtil class

因此,在这些情况下,必须定义类型。其中一种情况是您无法直接访问 layoutInflater,例如 ArrayAdapter getView();在这种情况下,他们离开了 DataBindingUtil 方法版本。

但是据我所知,只要 layoutInflater 可用,您就可以使用其他 inflate() 方法而无需引用布局 ID;例如,在您的代码段中,您可以将其替换为:

val binding = SplashFragmentBinding.inflate(layoutInflater)