android.widget.LinearLayout无法在片段的onCreateView上强制转换为android.support.v7.widget.RecyclerView

时间:2016-12-09 15:06:08

标签: android android-layout android-fragments

我正在尝试处理我正在创建List布局的材质设计项目。 错误如下:

java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v7.widget.RecyclerView at (package).ListContentFragment.onCreateView

片段类的OnCreateView代码如下:

RecyclerView recyclerView = (RecyclerView) inflater.inflate(
            R.layout.recycler_view, container, false);
    ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    return recyclerView;

片段的XML文件如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:background="?android:attr/selectableItemBackground"
android:padding="@dimen/md_keylines"> 

.....

</RelativeLayout>

完整的代码可以在Code on github

找到

1 个答案:

答案 0 :(得分:0)

布局管理器将项目视图放在RecyclerView内部,并确定何时重用用户不再可见的项目视图。

ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());

    recyclerView.setHasFixedSize(true);
mRecyclerView.setHasFixedSize(true);

    // use a linear layout manager
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setAdapter(adapter);