使用include作为根布局节点会抛出“Error inflating class include”异常。

23
我尝试根据操作系统版本使用不同的列表项布局。
因此,我创建了与条件关联的不同布局。其中一个是(在layout/search_result_list_item.xml中)。
<?xml version="1.0" encoding="utf-8"?>
<include xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    layout="@android:layout/simple_list_item_1">
</include>

它包括标准的"simple_list_item_1"。

在我的Java代码中,布局与列表关联如下:

    adapter = new SimpleCursorAdapter(getActivity(),
                                      R.layout.search_results_list_item,
                                      null,
                                      from,
                                      to,
                                      0);

当显示一个列表项时,会抛出以下异常:

android.view.InflateException: Binary XML file line #2: Error inflating class include
   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:576)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:385)
   at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
   at android.support.v4.widget.ResourceCursorAdapter.newView(ResourceCursorAdapt

什么有问题?不能将 <can't> 用作根项吗?尽管 ADT 允许使用它。


我不确定,但你是否尝试过将根视图设置为线性布局,并使用fill_parent来设置高度和宽度,然后在其中包含include视图? - blindstuff
是的,也许它可以工作,但我不想通过无用的中间视图(每行一个)来过度加载我的列表视图。 - DenisGL
那么就不要定义自己的 XML,而是将 simple_list_item_1 传递到适配器中,而不是你自己的。 - blindstuff
目的是根据操作系统版本使用不同的布局。 - DenisGL
你有没有找到解决办法?我也遇到了同样的问题。提前感谢。 :-) - Mira Weller
2个回答

33

如果还有其他人想知道,这就是答案:

<?xml version="1.0" encoding="utf-8"?>
<merge>
    <include xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        layout="@android:layout/simple_list_item_1">
    </include>
</merge>

是的,将<merge>标签作为根元素可以让您轻松地填充布局。谢谢! - jenzz
6
我了解到 "<merge /> 只能在有效的ViewGroup根元素中使用,且需要将 attachToRoot 设置为 true。" - Mickey Tin
1
@MickeyTin 你可能正在尝试使用inflate方法,并将第三个参数(attachToRoot)设置为“false”,或者像这个答案中所示,使用<merge>标签作为根。 - Takhion

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接