Thu*_*inh 12 java android view android-5.0-lollipop
我开始了一个针对Android Lollipop(21)的项目,并创建了一个自定义视图.当我为视图生成构造函数时,我得到了一个新的第4个构造函数,它比其他构造函数占用更多的参数.
public class FooView extends FrameLayout {
public FooView(Context context) {
super(context);
}
public FooView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FooView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
// This 4th constructor
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FooView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么我们需要它?如果我删除这个构造函数并在Lollipop上运行应用程序会发生什么?
信息来自官方文档
公共视图(上下文上下文、AttributeSet attrs、int defStyleAttr、int defStyleRes)
添加到 API 级别 21
从 XML 执行膨胀并从主题属性或样式资源应用特定于类的基本样式。View 的这个构造函数允许子类在膨胀时使用自己的基本样式。
在确定特定属性的最终值时,有四个输入起作用:
- 给定 AttributeSet 中的任何属性值。
- AttributeSet 中指定的样式资源(名为“style”)。
- 由 defStyleAttr 指定的默认样式。
- 由 defStyleRes 指定的默认样式。
- 该主题中的基本值。
这些输入中的每一个都被视为按顺序排列,首先列出的输入优先于随后列出的输入。换句话说,如果在您提供的 AttributeSet 中,则按钮的文本将始终为黑色,无论任何样式中指定了什么。
参数
- context 视图运行的上下文,通过它可以访问当前主题、资源等。
- attrs 扩充视图的 XML 标记的属性。
- defStyleAttr 当前主题中的属性,包含对为视图提供默认值的样式资源的引用。可以为 0 以不查找默认值。
- defStyleRes 为视图提供默认值的样式资源的资源标识符,仅当 defStyleAttr 为 0 或在主题中找不到时使用。可以为 0 以不查找默认值。
| 归档时间: |
|
| 查看次数: |
2117 次 |
| 最近记录: |