gpt4 book ai didi

java - 为什么我们需要 Lollipop 的第四个构造函数?

转载 作者:搜寻专家 更新时间:2023-10-30 21:12:21 27 4
gpt4 key购买 nike

我开始了一个针对 Android Lollipop (21) 的项目,并创建了一个自定义 View 。当我为 View 生成构造函数时,我得到了一个新的第四个构造函数,它比其他构造函数需要更多的参数。

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);
}
}

我的问题是,我们为什么需要它?如果我删除此构造函数并在 Lollipop 上运行该应用程序,会发生什么情况?

最佳答案

信息来自 official doc

public View (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Added in API level 21

Perform inflation from XML and apply a class-specific base style from a theme attribute or style resource. This constructor of View allows subclasses to use their own base style when they are inflating.

When determining the final value of a particular attribute, there are four inputs that come into play:

  1. Any attribute values in the given AttributeSet.
  2. The style resource specified in the AttributeSet (named "style").
  3. The default style specified by defStyleAttr.
  4. The default style specified by defStyleRes.
  5. The base values in this theme.

Each of these inputs is considered in-order, with the first listed taking precedence over the following ones. In other words, if in the AttributeSet you have supplied , then the button's text will always be black, regardless of what is specified in any of the styles.

Parameters

  • context The Context the view is running in, through which it can access the current theme, resources, etc.
  • attrs The attributes of the XML tag that is inflating the view.
  • 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.
  • defStyleRes A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.

关于java - 为什么我们需要 Lollipop 的第四个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com