findViewById()在访问自定义视图时返回null

问题描述 投票:-2回答:2

我创建了一个继承自android.view.View;的自定义视图,并将此视图添加到活动中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <view
        android:id="@+id/doorView"
        class="CustomView"
        android:layout_width="0dp"
        android:layout_height="220dp"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/..."/>
    </android.support.constraint.ConstraintLayout>

问题:findViewById总是返回null。以前叫过setContentView(R.layout.activity_main);

doorView = (DoorView) this.findViewById(R.id.doorView);

编辑:DoorView的构造函数:

public DoorView(Context context, AttributeSet attrs) {
    super(context);
}

我错过了什么?

android view
2个回答
0
投票

你需要将AttributeSet传递给超级构造函数。

更改

public DoorView(Context context, AttributeSet attrs) {
    super(context);
}

public DoorView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

否则,超类(例如android:id)读取的属性不会被设置。


0
投票

你没有doorView id,你有customView

你需要使用R.id.customView

© www.soinside.com 2019 - 2024. All rights reserved.