首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当您更改xml文件中的属性时,会调用自定义视图的哪个构造函数?

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

Stack Overflow用户
提问于 2021-04-04 03:24:33
回答 2查看 123关注 0票数 2

我正在创建自己的custom view

以下是MyCustomView.java的代码

代码语言:javascript
复制
    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文件:

代码语言:javascript
复制
<?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


/>

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-04 08:33:58

正如@Zain答复所描述的,当布局从XML中膨胀时,会调用双参数构造函数。

  • defStyleAttr是默认样式。它不直接指向样式,但允许您指向主题中定义的属性之一。 如果您正在子类一个小部件,并且没有指定您自己的默认样式,那么一定要在构造函数中使用父类默认样式(不要只传递0)。它只能是0,而不是寻找缺省值。 例如,在MaterialButtonR.attr.materialButtonStyle
  • defStyleRes是提供视图默认值的样式资源的资源标识符,仅当defStyleAttr为0或在主题中找不到时才使用。可以是0,以不查找默认值。 例如,在MaterialButtonR.style.Widget_MaterialComponents_Button

从本质上说,AttributeSet参数可以看作是布局中指定的XML参数的映射。

请记住样式优先顺序:

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

  • 给定AttributeSet中的任何属性值。
  • AttributeSet中指定的样式资源(名为"style")。
  • defStyleAttrdefStyleRes指定的默认样式。
  • 此主题中的基值。
票数 3
EN

Stack Overflow用户

发布于 2021-04-04 03:53:18

当您从XML访问自定义视图时,唯一需要的是双参数构造函数。

代码语言:javascript
复制
View(Context context, AttributeSet attrs)

3&4参数构造函数由超类调用,通过主题属性和直接默认样式资源提供默认样式。

代码语言:javascript
复制
View(Context context, AttributeSet attrs, int defStyleAttr)
View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
  • defStyleAttr参数是对主题中定义的样式属性的引用。
  • defStyleRes参数是对在styles.xml中定义的默认样式的引用。别担心,如果这个解释让你不满意的话。我将在关于属性和样式的一节中详细介绍。

源返回到本文

你也可以看看的问题

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66937759

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档