Search code examples
androidandroid-databinding

Send current view to ViewModel using DataBinding


I have a BindingAdapter like

@BindingAdapter({ "onGlobalLayout" })
public static void setOnGlobalLayout(View view, ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener) {
    ViewTreeObserver vto = view.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(onGlobalLayoutListener);
}

In XML I have a View like

    <View
        android:id="@+id/viewId"
        bind:onGlobalLayout="@{viewModel.onLayoutListener}"
        />

In ViewModel I have

public ViewTreeObserver.OnGlobalLayoutListener onLayoutListener(View view){
        return new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                 // get x,y,width, height of view           
            }
        };
}

Now I want to send the current View to ViewModel so I add a parametter View view to onLayoutListener but in XML I don't know how to send it.
Any help or suggestion would be great appreciated

UPDATE Thank @pskink for suggest a better way for checking layout change. With android:onLayoutChange I don't need BindingAdapter

<View
     android:id="@+id/viewId"
     android:onLayoutChange="@{viewModel.onLayoutListener(viewId)}"
/>

Java

public View.OnLayoutChangeListener onLayoutUpdateWeightSuccessfulListener(final View v) {
        return new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                    int oldLeft, int oldTop, int oldRight, int oldBottom) {
                    // left, top
            }
        };
    }

Solution

  • simply pass your View id, it should work

    bind:onGlobalLayout="@{viewModel.onLayoutListener(viewId)}"