Android databinding - How to get dimensions from dimens.xml

前端 未结 2 1379
独厮守ぢ
独厮守ぢ 2020-12-30 02:02

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:

<         


        
相关标签:
2条回答
  • 2020-12-30 02:16

    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.

    0 讨论(0)
  • 2020-12-30 02:36

    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.

    0 讨论(0)
提交回复
热议问题