我正在创建自己的custom 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
/>我的问题是:如果我在MyCustomView.java文件中更改自定义视图的属性,那么会调用文件的第二个或第三个构造函数吗?
发布于 2021-04-04 08:33:58
正如@Zain答复所描述的,当布局从XML中膨胀时,会调用双参数构造函数。
defStyleAttr是默认样式。它不直接指向样式,但允许您指向主题中定义的属性之一。
如果您正在子类一个小部件,并且没有指定您自己的默认样式,那么一定要在构造函数中使用父类默认样式(不要只传递0)。它只能是0,而不是寻找缺省值。
例如,在MaterialButton:R.attr.materialButtonStyle中defStyleRes是提供视图默认值的样式资源的资源标识符,仅当defStyleAttr为0或在主题中找不到时才使用。可以是0,以不查找默认值。
例如,在MaterialButton:R.style.Widget_MaterialComponents_Button中从本质上说,AttributeSet参数可以看作是布局中指定的XML参数的映射。
在确定特定属性的最终值时,有四个输入起作用:
AttributeSet中的任何属性值。AttributeSet中指定的样式资源(名为"style")。defStyleAttr和defStyleRes指定的默认样式。发布于 2021-04-04 03:53:18
当您从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中定义的默认样式的引用。别担心,如果这个解释让你不满意的话。我将在关于属性和样式的一节中详细介绍。你也可以看看这的问题
https://stackoverflow.com/questions/66937759
复制相似问题