本文为大家分享了类似微信朋友圈,点击+号图片,可以加图片功能,供大家参考,具体内容如下
xml:
<&#63;xml version="1.0" encoding="utf-8"&#63;>
NinePhotoView.java
public class NinePhotoView extends ViewGroup { public static final int MAX_PHOTO_NUMBER = 9; private int[] cOnstImageIds= { R.drawable.girl_0, R.drawable.girl_1, R.drawable.girl_2, R.drawable.girl_3, R.drawable.girl_4, R.drawable.girl_5, R.drawable.girl_6, R.drawable.girl_7, R.drawable.girl_8 }; // horizontal space among children views int hSpace = Utils.dpToPx(10, getResources()); // vertical space among children views int vSpace = Utils.dpToPx(10, getResources()); // every child view width and height. int childWidth = 0; int childHeight = 0; // store images res id ArrayListmImageResArrayList = new ArrayList (9); private View addPhotoView; public NinePhotoView(Context context) { super(context); } public NinePhotoView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public NinePhotoView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.NinePhotoView, 0, 0); hSpace = t.getDimensionPixelSize( R.styleable.NinePhotoView_ninephoto_hspace, hSpace); vSpace = t.getDimensionPixelSize( R.styleable.NinePhotoView_ninephoto_vspace, vSpace); t.recycle(); addPhotoView = new View(context); addView(addPhotoView); mImageResArrayList.add(new integer()); }
Measure
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int rw = MeasureSpec.getSize(widthMeasureSpec); int rh = MeasureSpec.getSize(heightMeasureSpec); childWidth = (rw - 2 * hSpace) / 3; childHeight = childWidth; int childCount = this.getChildCount(); for (int i = 0; i
我们的子View三个一排,而且都是正方形,所以我们上面通过循环很好去得到所有子View的位置,注意我们上面把子View的左上角坐标存储到我们自定义的LayoutParams 的left和top二个字段中,Layout阶段会使用,最后我们算得整个ViewGroup的宽高,调用setMeasuredDimension设置。
Layout
@Override protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { int childCount = this.getChildCount(); for (int i = 0; i
最核心的就是调用layout方法,根据我们measure阶段获得的LayoutParams中的left和top字段,也很好对每个子View进行位置排列。然后判断在图片未达到最大值9张时,默认最后一张是+号图片,然后设置点击事件,弹出对话框供用户选择操作。
Draw
不需要重写,使用ViewGroup默认实现即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。