最近在做项目,遇到了一个之前一直没解决的问题,那就是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()方法,至于这样是否可行,容我去试验一下。
代码可能写的不完善,如果哪里有什么问题,希望大家可以指出,不胜感激!