关于gridview的图片长宽处理

最近在做项目,遇到了一个之前一直没解决的问题,那就是Gridview展示商品的时候,图片的长宽问题。

众所周知,Android的机型太多,所以导致屏幕的大小也有各种各样。如果图片写死宽高的话,在不同屏幕的手机上显示的时候,可能会导致多种多样的问题。这个问题,在之前我也遇到过,不过一直没有解决方案,只能在Adapter里面动态设置ImageView的宽高,到这样,会导致代码变得更加难以维护。

不过,今天在做项目的时候忽然有了个想法,把这个想法实现的时候,似乎发现这个问题就这样迎刃而解了。

解决方案:图片的长宽要保持一致或者固定的比例,那么我想的方法,就是重写ImageView的onMeasure()方法。测量imageview的宽高,然后按照比例设置ImageView的宽高。这样问题就解决了。下面是代码:

View的代码

public class SquareImageView extends AppCompatImageView {

    private float heightPercent, screenPercent;

    public SquareImageView(Context context) {
        this(context, null);
    }

    public SquareImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SquareImageView);
        heightPercent = array.getFloat(R.styleable.SquareImageView_heightPercent, 0.4f);
        screenPercent = array.getFloat(R.styleable.SquareImageView_screenPercent, 0.42f);
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int result = (int) (DisplayUtils.getScreenWidth(getContext()) * screenPercent);
        setMeasuredDimension(result, (int) (heightPercent * result));
    }

    public void setScreenPercent(float screenPercent) {
        this.screenPercent = screenPercent;
        invalidate();
    }
}

布局文件,直接使用这个控件就行了:

<com.chinbo.square.SquareImageView
    android:id="@+id/iv"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:scaleType="centerCrop"
    android:src="@mipmap/image"
    app:heightPercent="1"
    app:screenPercent="0.5" />

还有一个自定义的属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SquareImageView">
        <attr name="heightPercent" format="float" />
        <attr name="screenPercent" format="float" />
    </declare-styleable>
</resources>

总共代码就上面这些,是不是很简单呢?如果我们想要设置什么比例的ImageView,我们只需要直接在布局文件设置就好了。

当然,这个只是解决了其中的一个问题,可能还会有另外的问题,比如,我ImageView的宽高,是后台传回来的,那该怎么办等一系列的。这问题,我想到的是动态设置percent,然后调用invalidate()方法,至于这样是否可行,容我去试验一下。

代码可能写的不完善,如果哪里有什么问题,希望大家可以指出,不胜感激!

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值