首页 > 解决方案 > 从消失后更改可见性后获取图像宽度

问题描述

ImageView我在里面有约束布局:

<ImageView
        android:id="@+id/iv_lottery"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_lottery_info"
        tools:visibility="visible" />

在我的片段中,当我收到网络响应时,我会显示ImageView并尝试从网络加载图像,Picasso并使用自动高度调整它的大小。

mIvLottery.setVisibility(View.VISIBLE);
Picasso.get().load(mLottery.getBanner()).resize(mIvLottery.getWidth(), 0).into(mIvLottery);

问题是:mIvLottery.getWidth()是0。

我该如何解决?

如果我将 xml 布局更改android:visibility from goneinvisibleor visible,一切正常。问题仅在默认可见性ImageView为时gone

标签: android

解决方案


因为mIvLottery可见性设置GONE为非常好,宽度为 0。

您在这里有几种解决方案,但不知道您的约束是什么,我想说最快的方法是从mLottery.getBanner().

否则,如果您需要计算屏幕上尚未显示的视图的宽度,您可以依赖measure()API。

所以调用measure()getMeasuredWidth()之后应该给你你正在寻找的宽度。请记住 measure 接受View.MeasureSpec作为参数,因此它取决于父布局选择哪些

mIvLottery.measure(UNSPECIFIED, AT_MOST);
int width = mIvLottery.getMeasuredWidth();

推荐阅读