自定义view的总结

一,view的绘制过程

  • onMeasure():测量view的宽度和高度,根据自身的MeasureSpec和具体背景设置而定,自身view的MeasureSpec由自身的LayoutParams和父类的MeasureSpec决定。
  • onLayout():计算view的位置,left,right,top,bottom,四个点的位置。
  • onDraw():在屏幕上渲染view。

二,自定义view的总结

  • 有四种自定义方式:
  1. 继承原生的view,实现ondraw()方法,设计规则特殊的view,这种方式,需要实现wrap_content和padding。
  2. 继承原生的viewgroup,设计新的布局方式,这种方式,需要实现测量onMeasure和布局onLayout。
  3. 继承特定的view,如textview,不需要实现wrap_content和padding,用来扩展view的功能。
  4. 继承特定的viewgroup,如LinearLayout,不用实现测量和布局的方法,用来设计基于此布局的新的布局。

三,自定义view的过程

  • 设计继承view的类,至少实现两个构造方法:
//如果View是在Java代码里面new的,则调用第一个构造函数
public CustomView(Context context)
{
    super(context);
}

// 如果View是在.xml里声明的,则调用第二个构造函数
// 自定义属性是从AttributeSet参数传进来的
public  CustomView(Context context,AttributeSet attrs)
{
    super(context, attrs);
}
  • 自定义属性的设计:有时候需要设计除了系统给定之外的其它属性,需要以下几步:
  1. 在资源文件中,增加对于自定义view的自定义属性的说明:

    

  1. 在具体使用CustomView的布局文件中加上这句代码,其中‘app’要和真正使用一致:**
xmlns:app="http://schems.android.com/apk/res-auto"
  1. 在布局设置CustomView的自定义属性:


  1. 在自定义View的构造函数中使用自定义属性:
public  CustomView(Context context,AttributeSet attrs)
{
    super(context, attrs);
    TypedArray ta = context.obtainStyledAttributes(arrs,R.styleable.CustomView);
    mcolor = ta.getColor(R.styleable.CustomView_custom_attr,Color.RED);
    
}

你可能感兴趣的:(自定义view的总结)