Java 当您更改xml文件中的属性时,会调用哪个自定义视图的构造函数?

Java 当您更改xml文件中的属性时,会调用哪个自定义视图的构造函数?,java,android,android-studio,android-theme,android-styles,Java,Android,Android Studio,Android Theme,Android Styles,我正在创建自己的自定义视图 下面是MyCustomView.java的代码 package com.krish.customviews import... public class MyCustomView extends FrameLayout{ public MyCustomView(@NonNull Context context){ super(context); init(

我正在创建自己的
自定义视图

下面是MyCustomView.java的代码

    package com.krish.customviews
    import...
    
    public class MyCustomView extends FrameLayout{
          public MyCustomView(@NonNull Context context){
               super(context);
               init();

          }
          public MyCustomView(@NonNull Context context, @Nullable AttributeSet attrs){
               super(context, attrs);
               init();

          }
          public MyCustomView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr){
               super(context, attrs, defStyleAttr);
               init();

          }
          private void init(){
          }
            
    }
和我的主_layout.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.krish.MyCustomView> 

//layout attributes


/>

//布局属性
/>

我的问题是:如果我更改.xml文件中自定义视图的属性,是否会调用
MyCustomView.java
文件的第二个或第三个构造函数?

从xml访问自定义视图时,只需要使用两个参数的构造函数

View(Context context, AttributeSet attrs)
3&4参数构造函数将由超类调用,以通过主题属性和直接默认样式资源提供默认样式

View(Context context, AttributeSet attrs, int defStyleAttr)
View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
  • defStyleAttr
    参数是对样式属性的引用 在主题中定义
  • defStyleRes
    参数是对默认样式的引用 在styles.xml中定义。如果这个解释是正确的,不要担心 你不满意。我将在本节中更深入地讨论细节 关于属性和样式

您还可以查看问题

,如从XML扩展布局时调用双参数构造函数所述

  • defStyleAttr
    是默认样式。它不直接指向样式,但允许您指向主题中定义的属性之一。
    如果您正在子类化一个小部件,并且没有指定自己的默认样式,那么请确保在构造函数中使用父类默认样式(不要只传递
    0
    )。它可以是
    0
    ,但不查找默认值。
    例如,在
    MaterialButton
    中:
    R.attr.materialButtonStyle

  • defStyleRes
    是为视图提供默认值的样式资源的资源标识符,仅当
    defStyleAttr
    为0或在主题中找不到时才使用。可以是
    0
    以不查找默认值。
    例如,在
    MaterialButton
    R.style.Widget\u MaterialComponents\u按钮中

AttributeSet
参数基本上可以看作是您在布局中指定的XML参数的映射。

在确定特定属性的最终值时,有 起作用的四个输入:

  • 给定
    属性集中的任何属性值
  • 属性集中指定的样式资源(名为
    “style”
  • defStyleAttr
    defStyleRes
  • 此主题中的基本值