Search code examples
androidandroid-databindingandroid-binding-adapter

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


Code B works well.

aHomeViewModel.isHaveRecord is LiveData<Boolean>, I hope to set different marginLeft based the value of aHomeViewModel.isHaveRecord .

Bur Code A get the following compile error, how can I fix it?

Cannot find a setter for <android.widget.TextView android:layout_marginLeft> that accepts parameter type 'float'

Code A

<TextView
     android:id="@+id/title_Date"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
    android:layout_marginLeft="@{aHomeViewModel.isHaveRecord? @dimen/margin1: @dimen/margin2 }"
  />

  <dimen name="margin1">10dp</dimen>
  <dimen name="margin2">5dp</dimen>

Code B

 <TextView
     android:id="@+id/title_Date"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginLeft="@dimen/margin1"
  />

  <dimen name="margin1">10dp</dimen>
  <dimen name="margin2">5dp</dimen>

BTW, the following code can work well.

android:padding="@{aHomeViewModel.displayCheckBox? @dimen/margin1 : @dimen/margin2 }"

Solution

  • 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 ;)