【问题标题】:android.view.InflateException: Binary XML file line #0: Error inflating class <unknown>!android.view.InflateException:二进制 XML 文件第 0 行:膨胀类 <unknown> 时出错!
【发布时间】:2018-06-06 10:44:16
【问题描述】:

这是可以显示错误的方法。

错误:

原因:

android.view.InflateException: Binary XML file line #0: Error inflating class <unknown>                                                                       

原因:

java.lang.reflect.InvocationTargetException

下面这段代码,

.inflate(R.layout.item_layout, parent, false); 

显示错误..

这是有错误的 onCreateViewHolder。

    @Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int 
viewType) {

    if (viewType == VIEW_TYPE_ITEM)
    {
        View view = LayoutInflater.from(activity)
                .inflate(R.layout.item_layout, parent, false);
        return new ItemViewHolder(view);
    }
    else if ( viewType == VIEW_TYPE_LOADING){
        View view = LayoutInflater.from(activity)
                .inflate(R.layout.item_loading, parent, false);
        return new LoadingViewHolder(view);
    }
    return null;
}

这是 item.layout xml 代码! 我认为这个 xml 文件与错误有关。所以我发布了这个。谢谢!!!

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height= "wrap_content"
    android:orientation="vertical"
app:cardElevation="10dp"
android:layout_margin="10dp"
>

<LinearLayout
    android:orientation="vertical"
    android:padding="10dp"
    android:layout_width="match_parent"
    android:background="?android:selectedWeekBackgroundColor"
    android:layout_height="wrap_content">

<TextView
    android:id="@+id/txtName"
    android:text="Name"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/txtLength"
    android:text="length"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

【问题讨论】:

  • 你能用 RecyclerView.Adapter 中getItemViewType 方法的代码更新你的问题吗?
  • 您还需要处理默认情况。可能是onCreateViewHolder return null

标签: android infinite-scroll android-inflate


【解决方案1】:

查看您的问题,您似乎对RecyclerView.Adapter 中的getItemViewType 方法有问题。

此方法的默认实现返回 0,假设适配器为单一视图类型。由于您期望不同的视图类型,请确保您已明智地覆盖此方法。

如果您还没有实现getItemViewType,那么您的onCreateViewHolder 将始终返回null ViewHolder,因为它永远不会匹配您的VIEW_TYPE_ITEMVIEW_TYPE_LOADING。解决方案是正确覆盖 getItemViewType 并返回适当的视图类型。

@Override
public int getItemViewType(int position) {
    final boolean shouldShowTypeItem = <your conditional statement>;
    return shouldShowTypeItem ? VIEW_TYPE_ITEM : VIEW_TYPE_LOADING;
}

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多