ListView中的ImageView扩展了最大宽度

时间:2012-09-05 18:00:21

标签: android android-layout android-imageview

我有一个ListView,其项目为ImageView s,以供讨论。我希望图像缩放到ListView行的宽度,并保持其纵横比。这是ListView项目布局的简化版本,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:padding="4dp" >

        <FrameLayout
            android:id="@+id/page_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" >

            <ImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:scaleType="fitCenter"
                android:src="@drawable/some_image" />
        </FrameLayout>
    </FrameLayout>

</LinearLayout>

ImageView的宽度为match_parent,并且它的所有祖先都是相同的。布局设计器显示ImageView的尺寸跨越整个宽度,但内部图像不是。

编辑:图像正确缩放。问题是列表视图行的高度使得宽度无法缩放到正确的大小。如果我使用fitXY,它会缩放宽度,但宽高比不正确。

任何想法? 感谢。

2 个答案:

答案 0 :(得分:4)

回答我自己的问题......

如果不创建自定义视图,我找不到任何方法来实现这一目标。简而言之,自定义视图将其自身的尺寸设置为其背后​​的可绘制的实际(非缩放)尺寸。

public class ResizableImageView extends ImageView {

    public static interface OnSizeChangedListener {

        void onSizeChanged(int width, int height);
    }

    private OnSizeChangedListener onSizeChangedListener = null;

    public ResizableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
        setMeasuredDimension(width, height);
        if (onSizeChangedListener != null) {
            onSizeChangedListener.onSizeChanged(width, height);
        }
    }

    public void setOnSizeChangedListener(OnSizeChangedListener listener) {
        this.onSizeChangedListener = listener;
    }
}

在我的情况下,我需要获取调整大小的值,以便调整其他视图的大小,从而调整侦听器接口。

答案 1 :(得分:0)

如果您想要保持宽高比,根据Android API Guide,我认为您必须更改android:scaleType =“fitCenter”for android:scaleType =“centerInside”或者android:scaleType =“centerCrop”,因为fitCenter不保持图像的纵横比。