我一直收到错误:
java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.widget.LinearLayout
每当执行以下操作时:
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
LinearLayout mLinearLayout = (LinearLayout) layoutInflater.inflate(R.layout.item, parent, false);
return new ViewHolder(mLinearLayout);
}
什么时候没有意义,因为这是我的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/item_text_view"/>
</LinearLayout>
因此XML文件的根应该是LinearLayout,因此inflater应该返回LinearLayout,它在哪里得到FrameLayout?
答案 0 :(得分:2)
替换
LinearLayout mLinearLayout = (LinearLayout) layoutInflater.inflate(R.layout.item, parent, false);
return new ViewHolder(mLinearLayout);
通过
View view = layoutInflater.inflate(R.layout.item, parent, false);
return new ViewHolder(view);
修改
ViewHolder
的公共构造函数需要View
而不是LinearLayout
。如果您需要访问此布局的子项,例如LinearLayout
,您必须从findViewById访问它,例如:
您的商品布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/your_linear_layout_id"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/item_text_view"/>
</LinearLayout>
您的ViewHolder
public class ExampleViewHolder extends RecyclerView.ViewHolder{
public ExampleViewHolder(View itemView) {
super(itemView);
LinearLayout linearLayout = (LinearLayout) itemView.findViewById(R.id.your_linear_layout_id);
}
}
onCreateViewHolder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.item, parent, false);
return new ViewHolder(view);
}