开发中遇到这样的需求,在页面中显示数量不确定的图片。如果不用自定义ViewGroup的话,只能在layout中一个一个的添加ImageView。这样做显然是不合适的,而且会有相当多的重复代码。面对这样的需求,我们可以通过自定义ViewGroup来解决。
自定义的ViewGroup:
/**
* Created by Answer on 2017/10/24.
*/
public class ImagesViewGroup extends ViewGroup {
private int maringTop = 12;
private List<ImageInfo> imageInfoList;
private Context context;
private ClickListener clickListener;
public ImagesViewGroup(Context context) {
this(context, null);
}
public ImagesViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ImagesViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ImagesViewGroup);
maringTop = (int) a.getDimension(R.styleable.ImagesViewGroup_ivg_marginTop, 12);
DisplayMetrics dm = context.getResources().getDisplayMetrics();
maringTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, maringTop, dm);
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSp