android.view.InflateException和java.lang.IllegalArgumentException

今天在写静态添加碎片的时候遇到一个错误:

Caused by: android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
                   Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
                   Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Must specify unique android:id, android:tag, or have a parent with an id for com.example.taoling.fragemntbook.LeftFragment
                      at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3717)

解决方法:
在fragment的布局文件(即xml文件)中将自己定义出来的控件加上一个android:id这个属性。然后重新运行app,问题解决。

在静态添加碎片的时候遇到这样一个异常,仔细看一下日志发现:
Must specify unique android:id, android:tag。大概意思就是必须要指定一个唯一的标识符,id或者tag等。

原因分析:

public class LeftFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.left_fragment,container,false);
        return view;
    }
}

中间使用了一个inflate方法,然后传入的第一个参数是一个R.layout.left_fragment,报错的地方就是此处的IllegalArgumentException(参数异常),然后进入到left_fragment.xml文件中,由于里面的自定义的控件没有加上android:id(相当于没有初始化改控件)。
InflateException源码如下:

/**
 * This exception is thrown by an inflater on error conditions.
 */
public class InflateException extends RuntimeException {

    public InflateException() {
        super();
    }

    public InflateException(String detailMessage, Throwable throwable) {
        super(detailMessage, throwable);
    }

    public InflateException(String detailMessage) {
        super(detailMessage);
    }

    public InflateException(Throwable throwable) {
        super(throwable);
    }

}

然后在进入RuntimeException源码中:
public class RuntimeException extends Exception {
static final long serialVersionUID = -7034897190745766939L;

/** Constructs a new runtime exception with {@code null} as its
 * detail message.  The cause is not initialized, and may subsequently be
 * initialized by a call to {@link #initCause}.
 */
public RuntimeException() {
    super();
}

注释中有一句话The cause is not initialized。造成该异常的原因是没有初始化。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值