View的四个构造函数

QuibblerQuibbler 2019-12-12 约 7 分钟 2465 次阅读

View的四个构造函数

一般自定义View,都需要继承View或者View的某个子类,必须要实现几个参数不同的构造方法:

public class MyView extends View {
    /**
    * Code中创建View时使用的构造方法
    * Simple constructor to use when creating a view from code.
    */
    public MyView(Context context) {
        super(context);
    }
    /**
    * 绘制Xml中View时使用的构造方法
    * Constructor that is called when inflating a view from XML.
    */
    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    /**
    * Perform inflation from XML and apply a class-specific base style from a theme attribute.
    */
    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    /**
    * Perform inflation from XML and apply a class-specific base style from a theme attribute or style resource.
    */
    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
}

第一个View(Context context),一般用于在代码中直接声明自定义View的时候使用

MyView mv = new MyView(mContext);

第二个构造函数View(Context context, @Nullable AttributeSet attrs)是在布局中使用自定义的View是系统会自动调用,生成自定义View实例。

第三个带三个参数View(Context context, @Nullable AttributeSet attrs, int defStyleAttr),它的作用是除了布局中指定的属性,另外在代码中指定默认风格。参数defStyleAttr是一种特殊属性类型既非整数也非字符串,而是参照类型(reference,需要在styles.xml中另外定义),官方给出的说明如下:

* @param defStyleAttr An attribute in the current theme that contains a
*        reference to a style resource that supplies default values for
*        the view. Can be 0 to not look for defaults.

obtainStyledAttibutes方法中几个参数的优先级如下:

  • 1、 Any value defined in the AttributeSet.
  • 2、The style resource defined in the AttributeSet (i.e. style=@style/blah).
  • 3、The default style attribute specified by defStyleAttr.
  • 4、The default style resource specified by defStyleResource (if there was no defStyleAttr).
  • 5、Values in the theme.

在第三个构造函数中,使用预定的一些style属性,通过obtainStyledAttibutes加载预先配置的属性:

public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        //自定义的reference属性
        super(context, attrs, R.attr.myStyle);
        //通过obtain加载入默认的style属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView, defStyleAttr, R.style.MyView);
        ... ...
    }

第四个用的比较少 API 21才引入,使用时需要注意兼容性问题。多出一个参数defStyleRes相对简单一些,是一个style资源的引用来为View提供属性默认值。但是优先级较低。

相关推荐

WilliamChart:轻量美观的 Android 图表库实战
精选开源

WilliamChart:轻量美观的 Android 图表库实战

WilliamChart:轻量美观的 Android 图表库实战数据可视化是运动、健康、金融、统计类 App 的刚需。MPAndroidChart 功能最全但偏重复杂,WilliamChart 走的则是"轻量 + 美观 + Kotlin 原生"路线——v3 用 Kotlin 完全重写,API 极简,一行 chart.animate(dataSet) 就能把数据画成带动画的折线/柱状/环形图,开箱即

175