Android 在更改可见性后获取图像宽度

Android 在更改可见性后获取图像宽度,android,Android,我的约束布局中包含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:la

我的约束布局中包含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" />
问题是:mIvLottery.getWidth为0

我怎样才能解决它

如果我在xml布局android:visibility中更改为不可见或可见,则一切正常。只有当ImageView的默认可见性消失时才会出现问题。

因为mIvLottery可见性设置为消失,所以宽度为0是完全正确的

这里有几种解决方案,但不知道约束条件是什么,我认为最快的方法是从mLottery.getBanner中提取宽度

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

因此,之后调用measure和getMeasuredWidth应该会给出所需的宽度。请记住,measure接受作为参数,因此它取决于父布局选择哪些布局

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

可能与我调用的mIvLottery.setVisibilityView.VISIBLE重复;在调用getWidth;之前;。将项目可见性设置为View.VISIBLE后未立即计算项目宽度?为什么?解决方案有效吗?更改视图的可见性并不意味着立即进行布局过程。但是还有其他一些API可以强制布局无效;度量值作为参数。LayoutParams.WRAP_内容在此上下文中无效。感谢您指出@EugenPechanec,我总是错误地使用layout params,从来没有出现过问题。我很乐意编辑我当前的答案,哪些是正确的衡量标准?最多不指定?
mIvLottery.measure(UNSPECIFIED, AT_MOST);
int width = mIvLottery.getMeasuredWidth();