Android - 如何测量包含在 constraintLayout 中的 'any size' View ?

标签 android android-constraintlayout

ConstraintLayout 需要两次通过才能测量任意大小的 View (尺寸为 0dp 的 View )。所以我有一个基于比率的 View ,我想在用户看到该 View 之前测量它的大小。如果重要的话,我正在做的是 recyclerview 的适配器。到目前为止我尝试过的是:

iv.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
width = iv.getMeasuredWidth();
height = iv.getMeasuredHeight();

这是布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginLeft="11dp"
        android:layout_marginRight="11dp"
        android:layout_marginTop="0dp"
        app:layout_constraintDimensionRatio="H,3:2"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
</android.support.constraint.ConstraintLayout>

但这总是返回 1 的宽度和 1 的高度。我怎样才能得到实际测量值?

我需要测量 View 的原因是构建一个 url。这是我需要的示例网址:

mywebsiteAtImgix.com/img/books/20170316171929_6b1c02a5.jpg?auto=compress&dpr=1&fit=clip&ixlib=java-1.1.1&q=75&w=1&h=1

更多信息: 我正在使用一家名为 imgix 的公司,他们会为我缩放所有图像。这非常快,并且它们缓存等,因此它对网络图像很有用。
不管怎样,请注意查询参数的宽度为“w”,高度为“h”。现在它们以 1 的形式出现,但是对于非 constraintlayout ImageView ,当我测量它时,我得到的尺寸没问题,并且从 imgix 返回的图像大小合适。如果我使用 1 和 1 作为尺寸,它会带回非常大的原始图像(2mb 到 5mb +)。我需要从 constraintLayout 中获取尺寸,这样我才能正确构建 URL。希望这能解决问题。

最佳答案

您可以使用 ViewTreeObserver.OnPreDrawListener在向用户显示布局之前直接获取图像的边界。

onPreDraw

boolean onPreDraw ()

Callback method to be invoked when the view tree is about to be drawn. At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs.

关于Android - 如何测量包含在 constraintLayout 中的 'any size' View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709179/

相关文章:

android - Xamarin.Forms 缺少方法异常 : 'Android.Support.V4.Widget.DrawerLayout.AddDrawerListener' not found

android - 使用带有浅色主题的 android.R.layout.simple_list_item_1

java - Android游戏中的零星延迟

android - 如何使用 ConstraintLayout 设置 maxHeight over DimensionRatio?

android - 在 ConstraintLayout 中使用 minHeight 查看

android - proguard-rules.pro 中的规则顺序重要吗?

android - 在 Android 上使用 Python 检索 WiFi 数据

android - ConstraintLayout 中的 RecyclerView 显示不正确

android - android 约束布局 1.1.3 的组可见性不起作用

android - 在 ConstraintLayout 中滚动浏览 RecyclerView 时如何折叠工具栏?