今天在写静态添加碎片的时候遇到一个错误:java
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,问题解决。android
在静态添加碎片的时候遇到这样一个异常,仔细看一下日志发现:
Must specify unique android:id, android:tag。大概意思就是必需要指定一个惟一的标识符,id或者tag等。web
缘由分析:app
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源码以下:ide
/** * 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;svg
/** 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。形成该异常的缘由是没有初始化。布局