Skip to content Skip to sidebar Skip to footer

How Can I Binding Different Value For Android:layout_marginleft Based Livedata In Android Studio?

Code B works well. aHomeViewModel.isHaveRecord is LiveData, I hope to set different marginLeft based the value of aHomeViewModel.isHaveRecord . Bur Code A get the fo

Solution 1:

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

publicclassBindingAdapters {
    @BindingAdapter("marginLeftRecord")
    publicstaticvoidsetLeftMargin(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 ;)

Post a Comment for "How Can I Binding Different Value For Android:layout_marginleft Based Livedata In Android Studio?"