在网上找了些仿微信群聊头像的开源库后,发现没特别好用的,或者说满足我需求的,就只好在别人的基础上改了下,也就有了这样的自定义控件了,以此来实现微信群聊头像的效果,效果图如下所示:
主要实现:
一、自定义viewGroup,以此来实现主要的代码逻辑
public class NineGridImageView<T> extends ViewGroup{
private int mRowCount; //行数
private int mColumnCount; //列数
private int mMaxSize = 9; //最大图片数
private int mGap; //宫格间距
private int parentWidth;//父组件宽
private int parentHeight;//父组件高
private List<ImageView> mImageViewList = new ArrayList<>();
private List<T> mImgDataList;
private NineGridImageViewAdapter<T> mAdapter;
public NineGridImageView(Context context) {
this(context,null);
}
public NineGridImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public NineGridImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NineGridImageView);
this.mGap = (int) typedArray.getDimension(R.styleable.NineGridImageView_imgGap, 8);
typedArray.recycle();
}
/**
* 设定宽高
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
parentWidth = measureWidth(widthMeasureSpec);
parentHeight = measureHeight(heightMeasureSpec);
setMeasuredDimension(parentWidth,parentHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
layoutChildrenView();
}
/**
* 为子ImageView布局
*/
private void layoutChildrenView(){
if(mImgDataList == null){
return;
}
int childrenCount = mImgDataList.size();
for(int i = 0; i < childrenCount; i++){
ImageView childrenView = (ImageView)getChildAt(i);
if(mAdapter != null){
mAdapter.onDisplayImage(getContext(), childrenView, mImgDataLi