【问题标题】:How to bind a view's width to the root view's width如何将视图的宽度绑定到根视图的宽度
【发布时间】:2020-10-05 07:22:34
【问题描述】:

我希望ImageView 的宽度与设备屏幕的大小相同。通常您会将layout_width 属性设置为match_parent。问题是我的ImageView 位于LinearLayout 内部,而HorizontalScrollView 位于HorizontalScrollView 内部。请参阅下面的代码

   <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 的宽度设置为根LinearLayout 的宽度,ID 为root_layout。 android数据绑定有可能吗?如果有其他方法可以达到同样的效果,请告知。

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

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

【问题讨论】:

    标签: android xml android-databinding


    【解决方案1】:

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

    您的 root_layout 有一个边距 - android:layout_margin="16dp",因此它的任何子代都不可能超出其在 LinearLayout 中的界限。

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

    此外,您似乎在HorizontalScrollView 中堆叠了一堆ImageView。您可能想改用RecyclerViewViewPager2

    【讨论】:

    • Recycler 视图似乎可以解决问题。谢谢我试图实现的是试图让 ImageView 的宽度与 Horizo​​ntalScrollView 中用户设备的宽度相匹配。
    猜你喜欢
    • 2014-03-30
    • 2021-03-31
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多