gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:15:27 24 4
gpt4 key购买 nike

我正在创建自己的自定义 View

这是 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(){
}

}

还有我的 main_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 文件中自定义 View 的属性,MyCustomView.java 文件的第二个或第三个构造函数是否会被调用?

最佳答案

@Zain answer所述当布局从 XML 扩展时,将调用双参数构造函数。

  • defStyleAttr 是默认样式。它并不直接指向样式,而是让您指向主题中定义的属性之一。
    如果您要对小部件进行子类化并且未指定您自己的默认样式,那么请务必在构造函数中使用父类的默认样式(不要只传递0)。它可以是0,只是为了不查找默认值。
    例如在 MaterialButton 中:R.attr.materialButtonStyle

  • defStyleRes 是为 View 提供默认值的样式资源的资源标识符,仅当 defStyleAttr 为 0 或无法在主题。可以为 0 以不查找默认值。
    例如在 MaterialButton 中:R.style.Widget_MaterialComponents_Button

AttributeSet 参数本质上可以被视为您在布局中指定的 XML 参数的映射。
Keep in mind the styling precedence order:

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

  • Any attribute values in the given AttributeSet.
  • The style resource specified in the AttributeSet (named "style").
  • The default style specified by defStyleAttr and defStyleRes
  • The base values in this theme.

关于java - 当您更改 xml 文件中的属性时,会调用自定义 View 的哪个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66937759/

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