gpt4 book ai didi

android - 哪个构造函数被调用来查看?

转载 作者:IT老高 更新时间:2023-10-28 23:09:49 24 4
gpt4 key购买 nike

我的自定义 View 是从 View 扩展而来的。有 3 个 View 构造函数:

  1. View(Context context, AttributeSet attrs, int defStyle)
  2. View(上下文上下文,AttributeSet attrs)
  3. 查看(上下文上下文)

从我的 Activity 中,我调用 std.setContentView(R.layout.main)。在我看来,第二个构造函数正在被调用。为什么是第二个?如何提前知道会调用哪一个以及为什么?

最佳答案

来自 Android 开发者网站的 View 文档:

public View (Context context)

Simple constructor to use when creating a view from code.

因此,您可以使用此构造函数在 Java 中创建 View 。当你从 XML 膨胀时它不会被调用。

public View (Context context, AttributeSet attrs)

Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.

The method onFinishInflate() will be called after all children have been added.

所以当你没有指定样式时,当你从 XML 扩展 View 时会调用这个构造函数。

public View (Context context, AttributeSet attrs, int defStyle)

Perform inflation from XML and apply a class-specific base style. This constructor of View allows subclasses to use their own base style when they are inflating. For example, a Button class's constructor would call this version of the super class constructor and supply R.attr.buttonStyle for defStyle; this allows the theme's button style to modify all of the base view attributes (in particular its background) as well as the Button class's attributes.

您应该实现所有这些构造函数,但您可以通过调用 this(context, null)this(context, attrs, 0) 将所有工作放在第三个构造函数中 分别为前两个。

关于android - 哪个构造函数被调用来查看?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8113621/

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