首页 > 解决方案 > 如何在 Horizo​​ntalScrollView 内获取 ImageView 全宽

问题描述


我在 Horizo​​ntalScrollView 中放置了一个非常宽的图像。
ImageView/ScrollView 高度是动态的,因为我将高度设置为 0dp 并添加了约束。
由于 ImageView 的比例类型为 fitStart 且 adjustViewBounds 为 true - 正在调整图像的宽度。

XML:

     <HorizontalScrollView
        android:id="@+id/mapScrollView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="10dp"
        app:layout_constraintBottom_toTopOf="@id/playButton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.constraint.ConstraintLayout
            android:id="@+id/mapLayout"
            android:layout_width="wrap_content"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/mapImage"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:adjustViewBounds="true"
                android:scaleType="fitStart"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <com.gigi.testmap.activities.quest.QuestMapPathView
                android:id="@+id/mapLinesView"
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:layout_constraintBottom_toBottomOf="@id/mapImage"
                app:layout_constraintEnd_toEndOf="@id/mapImage"
                app:layout_constraintStart_toStartOf="@id/mapImage"
                app:layout_constraintTop_toTopOf="@id/mapImage" />

        </android.support.constraint.ConstraintLayout>

    </HorizontalScrollView>


我正在尝试获取 ImageView 宽度(总宽度,可见和不可见部分)。获取 ScrollView 总宽度也将有所帮助。
我的目标是将按钮放置在地图顶部根据渲染的 ImageView 的宽度和高度计算的位置。

我正在使用 Glide 加载图像:

final ImageView mapImage = mActivity.findViewById(R.id.mapImage);
Glide.with(mActivity).load(R.drawable.fullmap).into(mapImage);

mapImage.getViewTreeObserver().addOnGlobalLayoutListener(new 
ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        mapImage.getWidth(); // --> returns 0    
        mapImage.getViewTreeObserver()
             .removeOnGlobalLayoutListener(this);
    }
 });

我尝试使用树视图观察者的全局布局侦听器获取宽度,但我得到的只是 0。尽管返回了正确的高度

任何帮助将不胜感激,非常感谢。

标签: androidandroid-imageviewandroid-scrollview

解决方案


我没有使用 Glide 的经验。

您正在设置所有视图/容器android:layout_height="0dp" ,首先尝试将其更改为任何其他任意值或wrap_content.

您没有附上您如何尝试获得高度的代码。

你试过了吗mapImage.getHeight()


推荐阅读