如何将视图的宽度绑定到根视图的宽度

How to bind a view's width to the root view's width

我希望 ImageView 的宽度与设备屏幕的宽度相同。通常您会将 layout_width 属性设置为 match_parent。问题是我的 ImageViewLinearLayout 里面,而 LinearLayoutHorizontalScrollView 里面。请参阅下面的代码

   <LinearLayout
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:orientation="vertical">

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:scrollbars="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/fragment_get_trending_image_backdrop1"
                android:layout_width='@{String.valueOf(rootLayout.width)+"dp"}'
                android:layout_height="200dp"
                android:src="@drawable/cassidy"
                android:scaleType="fitXY"
                tools:srcCompat="@tools:sample/backgrounds/scenic" />
//....other imageviews

我想在运行时将 ImageView 的宽度设置为 ID 为 root_layout 的根 LinearLayout 的宽度。 android 数据绑定可能吗?如果有其他方法可以达到同样的目的,请指教。

我在尝试编译时收到此错误消息

Could not resolve the two-way binding attribute 'width' on type 'android.widget.LinearLayout'

你不能做你想做的事。 首先,这可能是一个 XY 问题。你想达到什么目的?

您的 root_layout 有一个边距 - android:layout_margin="16dp",因此它的任何子级都不可能在 LinearLayout.

中超出其边界

因此,您可以设置 android:layout_margin="0dp"(或删除该属性)。

此外,您似乎在 HorizontalScrollView 中堆叠了一堆 ImageView。您可能需要使用 RecyclerViewViewPager2