Android数据绑定的疑惑

Ale*_*dro 1 data-binding android android-context android-recyclerview android-databinding

It seems to me that Android Data Binding is an interesting tool, but it doesn't tie very well with the (overly) complex architecture of Android. Many example or tutorials show only some basic scenario that obviously works, but when things become harder then problems arise.

For example: many views (like RecyclerView or ViewPager) require adapters or decorators that need Context and it seems wrong to pass the Context to every ViewModel because it breaks the separation of layers.

ViewFlipper: how do you show next or previous by just binding a property of the ViewModel?

How would you bind a RecyclerView with a LinearLayout, an ItemAnimation and an ItemDecoration? Can you show some real-world complex example of Android Data Binding at work?

Geo*_*unt 5

您可能对这两篇文章感兴趣:

在 RecyclerView 中使用数据绑定:https : //medium.com/google-developers/android-data-binding-recyclerview-db7c40d9f0e4

在没有 RecyclerView 的列表中使用数据绑定(例如 LinearLayout):https ://medium.com/google-developers/android-data-binding-list-tricks-ef3d5630555e

使用 ItemDecoration,您必须添加自己的 BindingAdapter,因为 RecyclerView 允许多个项目装饰。这样的事情应该工作:

@BindingAdapter("itemDecoration")
public static void setItemDecoration(RecyclerView view, ItemDecoration old,
        ItemDecoration newVal) {
    if (old != null) {
        view.removeItemDecoration(old);
    }
    if (newVal != null) {
        view.addItemDecoration(newVal);
    }
}
Run Code Online (Sandbox Code Playgroud)

您关于 Context 的问题有点令人困惑。我试图想象在数据绑定中您将如何需要 Context。数据绑定表达式不允许,new因此您将无法以这种方式创建。也许您正在考虑使用一些表示代替:

@BindingAdapter("dividerDirection")
public static void setItemDecoration(RecyclerView view, int oldDirection, int newDirection) {
    if (oldDirection != newDirection) {
        ItemDecoration decoration =
                new DividerItemDecoration(view.getContext(), newDirection);
        ItemDecoration old = ListenerUtil.trackListener(view, decoration, R.id.decoration);
        if (old != null) {
            view.removeItemDecoration(old);
        }
        view.addItemDecoration(decoration);
    }
}
Run Code Online (Sandbox Code Playgroud)

它会像这样绑定:

<android.support.v7.widget.RecyclerView
     app:dividerDirection="@{DividerItemDecoration.HORIZONTAL}" .../>
Run Code Online (Sandbox Code Playgroud)

对于其他用途,您会在布局中自动获得一个内置的“上下文”变量,您可以将其传递给您调用的任何方法。它是绑定视图层次结构的根视图的上下文,应该可以满足您的大部分需求。对于大多数用途,您不需要在模型中传递上下文。

我希望这也应该回答您关于 ItemAnimator 的问题,尽管您不需要特殊的 BindingAdapter 来使用属性,因为它已经有一个 setter:

<android.support.v7.widget.RecyclerView
     app:itemAnimator="@{model.animator}" .../>
Run Code Online (Sandbox Code Playgroud)