今天看了鸿洋大神的自定义viewgroup,现在做一下笔记

首先,创建默认构造方法,如下所示
public FlowLayout(Context context) {
super(context,null);
}

public FlowLayout(Context context, AttributeSet attrs) {
super(context, attrs,0);
}

public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

先说一下自定义viewgroup的流程。
onMeasure(用于测量父类的宽高)–>onlayout(用于子类测量以及位置的摆放)

1.重写onMeasure方法:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//获取父类传递过来的参数, widthMeasureSpec用于获取父容器测量的宽度和测量模式
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

int modeWidth = MeasureSpec.getMode(widthMeasureSpec);int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

}

测量模式有以下三种:
MeasureSpec.EXACTLY:对应的是MATCH_PARENT,FILL_PARENT以及精确值,例如50dp之类
MeasureSpec.AT_MOST:对应的是WRAP_CONTENT
MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式。

接着,遍历所有子view
int cCount = getChildCount();
for (int i=0;i< cCount;i++){
View child = getChildAt(i);
measureChild(child,widthMeasureSpec,heightMeasureSpec);

//MarginLayoutParams从哪里来呢?我们一般会重写generateLayoutParams(AttributeSet attrs)方
//法,如下所示
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
}

@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new MarginLayoutParams(getContext(),attrs);
}

generateLayoutParams确定了子类的layouparams,如果需要自定义,那么继承ViewGroup.LayoutParams,重写方法即可。

最后,调用setMeasuredDimension(width,height);
将测量到的宽高传入即可。

2.重写onLayout方法
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
int childCount = this.getChildCount();
for (int j=0;j< cCount;j++){
View child = getChildAt(j);
LayoutParams lParams = (LayoutParams) child.getLayoutParams();
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
lParams.top + childHeight);
}
}

获取对应的子view,然后对子view进行位置摆放。OVER!

更多相关文章

  1. Android(安卓)Viewpager拦截 左右滑动
  2. [Android]单元测试实例
  3. Android删除短信的方法
  4. Android(安卓)ListView实现方法一(ListActivity)
  5. Android(安卓)一键退出APP 实现
  6. Android(安卓)自定义Dialog,以及失去焦点之后,Dialog消失的解决
  7. js与android iOS 交互兼容
  8. Android(安卓)面试--请描述一下Activity的生命周期?
  9. Android(安卓)Handler 分析

随机推荐

  1. 用eclipse开发android时两个组件总是重叠
  2. Android OKhttp 上传文件袋参数
  3. 收集的一些android open source app
  4. Android(安卓)存储路径
  5. Android界面设计
  6. android带彩色下划线的tab移动导航
  7. android sdk无法更新怎么办?如何解决
  8. 几本适合新手的Android电子书(提供下载)
  9. Android屏幕切换效果实现
  10. Android(安卓)App增量更新详解及实例代码