Android应用程序当中GridView显示不同大小图片时Item挤出问题解决办法

1、问题说明

        在开发GridView的时候有这样的一个需求,即从网络上下载相应的图片然后显示在GridView当中,显示效果如下:

 

       

        以上的图片,不同的图片是对齐的,没有图片挤出,太大或者太小的问题,做出这种效果的前提是,图片大小是一样的。但是,在实际情况下,图片的大小多数情况下是不一致的,就会造成如下的效果,



图片大小不同,导致大的图片将下面的文字挤出GridView中的Item,解决方案很简单,只要将显示在GridView中的Item的ImageView重写一下,控制一下大小即可。这种方式,同本博客ScrollView嵌套GridView、ListView的解决办法类似。

2、复写ImageView

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class SquareImageView extends ImageView {

    public SquareImageView(Context context) {
        super(context);
    }

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

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // Snap to width
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
    }
}

将现有的SquareImageView代替原来的ImageView,

 <com.remind.view.SquareImageView
        android:id="@+id/img_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true" />

3、修改后效果

 

现在图片挤出的效果不见了,GridView当中每个Item大小都是一致的。

posted @ 2016-08-11 10:05  安谧世界  阅读(1073)  评论(0编辑  收藏  举报