In fact, it can also be implemented with a custom View. I am lazy, so I use LayerDrawable to create a new Drawable resource implementation.
For example, the 4-square grid has a similar principle to the 9-square grid. The position of each icon needs to be slowly adjusted with margins to achieve the desired effect.
The effect is as follows:
Double avatar:
Three avatars:
Four avatars:
accomplish:
/**
* 使用LayerDrawable生成四宫格头像(包含双人、三人头像)
*
* @param drawables 头像数组
* @return 四宫格头像
*/
private Drawable createHeaderForSms(Drawable[] drawables) {
int size = drawables.length;
if (size == 1) {
return drawables[0];
}
int dp34 = (int) context.getResources().getDimension(R.dimen.dp_34);
int dp24 = (int) context.getResources().getDimension(R.dimen.dp_24);
int dp6 = (int) context.getResources().getDimension(R.dimen.dp_6);
int dp48 = (int) context.getResources().getDimension(R.dimen.dp_48);
LayerDrawable la = new LayerDrawable(drawables);
// 其中第一个参数为层的索引号,后面的四个参数分别为left、top、right和bottom
switch (drawables.length) {
case 2:
la.setLayerInset(0, 0, 0, dp34, dp34);
la.setLayerInset(1, dp34, dp34, 0, 0);
break;
case 3:
la.setLayerInset(0, dp24, dp6, dp24, dp48);
la.setLayerInset(1, 0, dp48, dp48, dp6);
la.setLayerInset(2, dp48, dp48, 0, dp6);
break;
case 4:
la.setLayerInset(0, 0, 0, dp48, dp48);
la.setLayerInset(1, dp48, 0, 0, dp48);
la.setLayerInset(2, 0, dp48, dp48, 0);
la.setLayerInset(3, dp48, dp48, 0, 0);
break;
}
return la;
}