You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义View调用findViewById()返回null问题排查

问题解析:findViewById获取自定义View返回null的原因及修复方案

嘿,我来帮你排查下这个问题,主要有两个关键错误导致了findViewById返回null:

1. 布局文件中自定义View的类名写错了

你的自定义View类名是DoorView,但布局里的class属性写的是CustomView——这就导致系统找不到对应的View类,根本没法实例化出DoorView对象,自然findViewById就拿不到实例了。

另外要注意:如果你的DoorView不在项目的默认包下,必须写完整的全限定类名(包名+类名),比如com.yourproject.ui.DoorView,不然系统也找不到这个类。

修正后的布局代码:

<?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"
        <!-- 替换成你的实际包名+DoorView类名 -->
        class="com.yourpackage.DoorView"
        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>

2. 构造方法没有正确传递AttributeSet参数

当系统从XML布局初始化View时,会调用带AttributeSet参数的构造方法,但你的代码里只调用了super(context),没有把attrs传递给父类。这会导致View无法正确解析布局中的属性(比如宽高、margin等),甚至引发初始化异常,导致View实例化失败。

修正后的DoorView构造方法:

public DoorView(Context context, AttributeSet attrs) {
    super(context, attrs); // 必须把attrs传递给父类构造方法
}

另外,为了兼容更多场景,建议补充另外两个常用的构造方法:

// 代码中直接new实例时调用
public DoorView(Context context) {
    this(context, null);
}

// 带默认样式的构造方法
public DoorView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

把这两处错误修复后,再重新运行,应该就能正常通过findViewById(R.id.doorView)获取到DoorView实例了。

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:11:59