How can I binding different value for android:layout_marginLeft based LiveData in Android Studio?

To get this working you will have to define a custom @BindingAdapter:

public class BindingAdapters {
    @BindingAdapter("marginLeftRecord")
    public static void setLeftMargin(View view, boolean hasRecord) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
        params.setMargins(
                hasRecord ? (int) view.getResources().getDimension(R.dimen.margin1)
                          : (int) view.getResources().getDimension(R.dimen.margin2)
                , 0, 0, 0);
        view.setLayoutParams(params);
    }
}

Whether you need LinearLayout.LayoutParams or others depends on the parent of you TextView.

To use this adjust your xml to:

<TextView
    android:id="@+id/title_Date"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    marginLeftRecord="@{aHomeViewModel.isHaveRecord}" />

Tested and working 😉

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top