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

Android自定义View中获取LinearLayout引用空指针如何解决

问题原因

你调用findViewById的逻辑存在错误:View类自带的findViewById方法,只会从当前View本身及其子View的视图树中查找匹配id的控件,而你要找的LinearLayout是当前自定义input View的父容器,不在查找范围内,自然返回null,调用getChildCount时就触发空指针异常。

解决方案

方案1:直接获取父容器(最稳妥,无耦合)

因为你的自定义input View的直接父布局就是目标LinearLayout,点击时直接通过getParent()获取父容器即可,不需要依赖父布局的id,示例代码如下:
首先修改input类,添加成员变量保存xml属性集,方便后续判断required属性:

public class input extends TextView{
    // 新增成员变量保存xml属性
    private AttributeSet mAttrs;

    public input(Context context, AttributeSet attr) {
        super(context, attr, getIdentifier(context,attr));
        mAttrs = attr;
    }

    @Override
    public void onFinishInflate() {
        setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 直接获取父布局
                LinearLayout layout = (LinearLayout) view.getParent();
                for(int i=0; i<layout.getChildCount(); i++) {
                    View child = layout.getChildAt(i);
                    // 匹配第一个input控件
                    if(child instanceof input && i == 0) {
                        input firstInput = (input) child;
                        // 判断是否存在required属性
                        String requiredVal = firstInput.mAttrs.getAttributeValue(null, "required");
                        boolean hasRequired = requiredVal != null;
                        // 后续写你的业务逻辑即可
                    }
                }
            }
        });
    }
}

方案2:通过Activity查找根布局

如果你必须通过id查找父布局,可以将上下文强转为Activity后再调用findViewById,但要注意上下文必须是Activity类型,否则会抛出类型转换异常:

// 替换你原来获取layout的代码
LinearLayout layout = (LinearLayout) ((Activity)getContext()).findViewById(R.id.mainLinearLayout1);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:06:03