今天在写静态添加碎片的时候遇到一个错误:
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。造成该异常的原因是没有初始化。