目前自己的状态还是不是太好,太容易受到别人对人对自己的影响,如何做到只关注自己学习的状态,这确实是一个比较严肃点问题。
本次的学习总结也是比较简单的自定义ViewGroup,主要是实现标签(Tag)在这个ViewGroup中能够正确的测量和摆放。对应的两个重要的方法:onMeasure()、onLayout()。
特别注意:List<List <View>>的赋值过程。在测量ViewGroup子孩子的过程中,需要提前调用
measureChild(childView,widthMeasureSpec,heightMeasureSpec);
上面这个方法需要传入父布局的
,widthMeasureSpec,heightMeasureSpec
才能通过
int childWidth = childView.getMeasuredWidth();
的方式得到子孩子的宽高。
public class TagViewGoup extends ViewGroup {
int width = 0,height = 0;
int childCount;
private static final String TAG = "TagViewGoup";
List<List<View>> outList = new ArrayList<>();
public TagViewGoup(Context context) {
super(context);
}
public TagViewGoup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TagViewGoup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
outList.clear();
List<View> innerList = new ArrayList<>();
outList.add(innerList);
int width = 0;
int Maxwidth = 0;
int layoutWith = MeasureSpec.getSize(widthMeasureSpec);
int childCount = getChildCount();
for(int i = 0;i<childCount;i++){
View childView = getChildAt(i);
measureChild(childView,widthMeasureSpec,heightMeasureSpec);
int childWidth = childView.getMeasuredWidth();
width +=childWidth;
if(width >layoutWith){
Log.d(TAG, "onMeasure: ");
int currentMax = width - childView.getMeasuredWidth();
Maxwidth = Math.max(Maxwidth,currentMax);
width = 0;
height += childView.getMeasuredHeight();
innerList = new ArrayList<>();
outList.add(innerList);
}else {
height = childView.getMeasuredHeight();
}
innerList.add(childView);
setMeasuredDimension(Maxwidth,height);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int orginBottom = outList.get(0).get(0).getMeasuredHeight();
int left = 0,top = 0,bottom = orginBottom,right = 0;
for (List<View> viewList:outList){
for(View childView:viewList){
right += childView.getMeasuredWidth();
childView.layout(left,top,right,bottom);
left += childView.getMeasuredWidth();
}
bottom += orginBottom;
top += orginBottom;
left =0;
}
}
}