I want to set margins based on dimensions i have created in dimens.xml The dimensions it sself works fine, its just data binding cant find it in the case below:
<
Almost the same solution, but using Kotlin:
In file BindingAdapters.kt add:
@BindingAdapter("layoutMarginBottom")
fun setLayoutMarginBottom(view: View, dimen: Float) {
view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
bottomMargin = dimen.toInt()
}
}
Usage in layout:
<LinearLayout
app:layoutMarginBottom="@{viewModel.type == Type.SMALL ? @dimen/margin_small : @dimen/margin_large}"
You can write similar method for top
, start
, end
margins.
The problem here is not with dimensions, but with android:layout_marginBottom
. There is no built-in support for any LayoutParams
attributes. This was done to remove the "foot gun" that many might use to bind variables to LayoutParams
and maybe attempt to use data binding to animate their positions this way.
Data Binding is perfect to be used in your example and you can easily add your own. It would be something like this.
@BindingAdapter("android:layout_marginBottom")
public static void setBottomMargin(View view, float bottomMargin) {
MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin,
layoutParams.rightMargin, Math.round(bottomMargin));
view.setLayoutParams(layoutParams);
}
You would, of course, also add the left, top, right, start, and end BindingAdapters
as well.