【发布时间】:2020-06-14 23:04:48
【问题描述】:
所以我有这个自定义布局。
public class MyCustomView extends ConstraintLayout {
private Button myFancyButton;
public MyCustomView (@NonNull Context context, AttributeSet attrs) {
super(context,attrs);
myFancyButton = findViewById(R.id.button); //THIS IS NULL
}
public void init(){
myFancyButton = findViewById(R.id.button); //WORKS GREAT
}
}
问题是我宁愿不创建一个函数“init”来完成适合构造函数的工作。我面临的问题是在构造函数中调用 findViewById 导致它为空。在 MyCustomView 对象上使用 init 函数就可以了。但我更愿意在构造函数中这样做。
对应的 XML 文件如下所示。
<?xml version="1.0" encoding="utf-8"?>
<se.test.test.test.MyCustomView xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<Button
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="B1"
android:textSize="30sp"/>
</se.test.test.test.MyCustomView>
【问题讨论】: