首页 > 解决方案 > 如何在自定义视图中解决 InflateException

问题描述

我的问题是关于 Android/Java 的。

我的 main.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <org.javaforum.input
        android:layout_width="wrap_content"
        android:inputType="textEmailAddress"
        android:layout_height="wrap_content"
        oninvalid="this.setCustomValidity('SO - Please enter a correct E-Mail!!!')"
        android:hint="Enter your E-Mail"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"/>

</LinearLayout>

我的输入.java:

public class input extends TextView{
    public input(Context context, AttributeSet attr) {
        super(context, attr, getIdentifier(context,attr));
        if(existsoninvalid(attr)){
            //Code
        }
    }
    
    public static boolean existsoninvalid(AttributeSet attr){
        for(int f=1; f<=attr.getAttributeCount(); f++){
            if(attr.getAttributeName(f)=="oninvalid"){//Here must be the error
                //Code
            }
        }
        return false;
    }

    @Override
    public void onFinishInflate() {
        
    }
}

该应用程序因异常而崩溃:

java.lang.RuntimeException:无法启动活动 ComponentInfo{org.javaforum/org.javaforum.MainActivity}:android.view.InflateException:二进制 XML 文件第 7 行:二进制 XML 文件第 7 行:膨胀类 org.javaforum 时出错。输入

但是当我删除它时:

if(attr.getAttributeName(f)=="oninvalid"){//Here must be the error
        //Code
}

该应用程序不会崩溃,我也没有收到任何异常。我不知道为什么。哪里有问题?我该如何解决?

标签: javaandroidandroid-custom-viewinflate-exception

解决方案


该异常有一个嵌套的“由”异常,其中包含更多详细信息。

索引是从零开始的。您的 for 循环从 1 开始,在另一端结束。

此外,在 Java 中使用equals()并不能==用于字符串比较。(这不会导致崩溃,但也不会按照您想要的方式工作。)


推荐阅读