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

标签 android android-layout

我的自定义 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/

相关文章:

android - 如何在android中使用 picasso 库将背景图像设置为 Activity 布局

java - 在 SearchView 上获取 Null 对象引用

android - 无法在 Android 中使用 Pop 接收邮件

java - 将 TextView 添加到布局时出现 NullPointerException

android - AppCompat 工具栏不显示

android - 使用样式设置 layout_width、layout_height

android - 快速适配器位置

java - NullpointerException 尝试调用虚拟方法 'void android.widget.Button.setOnClickListener

android - addView 在 android 2.2 上崩溃,在 2.1 和 1.6 上工作正常

java - fragment 未显示其完整宽度和高度