Warm tip: This article is reproduced from serverfault.com, please click

android-自定义视图上的findViewById抛出null

(android - findViewById on custom view throws null)

发布于 2020-12-24 11:09:26

在解释问题之前,我想说我已经看过所有相关问题,但是没有一个对我有用。

我是Android的初学者。我使用的是自定义视图类,假设CustomView看起来像这样:

class CustomView(context: Context?,attributeSet: AttributeSet) : View(context) {

    class CustomView constructor(context: Context?, attributeSet: AttributeSet){

    }
    var number = 1
}

我在片段资源中夸大了这种观点,例如:

<com.example.myapp.CustomView
     android:id="@+id/custom_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>

但是现在,每当我尝试获取自定义视图时,它都为null。所有同级视图都可以正常工作。

val root = inflater.inflate(R.layout.fragment_main, container,false)
val customView: CustomView = root.findViewById(R.id.custom_view)

它抛出一个错误

java.lang.IllegalStateException: findViewById(R.id.custom_view) must not be null
Questioner
iamsubingyawali
Viewed
0
cactustictacs 2020-12-24 19:28:09

你需要将该AttributeSet参数传递View超类构造函数:

要允许Android Studio与你的视图进行交互,你至少必须提供一个以ContextAttributeSet对象为参数的构造函数。该构造函数允许布局编辑器创建和编辑视图的实例。

https://developer.android.com/training/custom-views/create-view#subclassview

所以:

class CustomView(context: Context?,attributeSet: AttributeSet) : View(context, attributeSet) {

如果愿意,这是标准的样板文件,重载的自定义视图构造函数(IDE将为你生成):

class CustomView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr)

那有一些极端的案例主题折衷,但是通常没问题,并且可以处理系统要使用的任何构造函数。

(而且你CustomView在代码中不需要该嵌套类)