自定义view的总结

2017-11-03  本文已影响0人  CodeManLB

一,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是在Java代码里面new的,则调用第一个构造函数
public CustomView(Context context)
{
    super(context);
}

// 如果View是在.xml里声明的,则调用第二个构造函数
// 自定义属性是从AttributeSet参数传进来的
public  CustomView(Context context,AttributeSet attrs)
{
    super(context, attrs);
}
  1. 在资源文件中,增加对于自定义view的自定义属性的说明:
<declare-styleable name="CustomView">
    <attr name="custom_attr" format="color|drawable">
</declare-styleable>
  1. 在具体使用CustomView的布局文件中加上这句代码,其中‘app’要和真正使用一致:**
xmlns:app="http://schems.android.com/apk/res-auto"
  1. 在布局设置CustomView的自定义属性:
<CustomView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:custom_attr="#fff">
</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);
    
}
上一篇 下一篇

猜你喜欢

热点阅读