Reputation: 5904
I have a problem in my NavigationDrawer layout with error:
android.widget.RelativeLayout cannot be cast to android.support.v7.widget.RecyclerView
This is my onCreateView:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRecyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_drawer, container, false);
mRecyclerView.setClipToPadding(false);
mAdapter = new NavigationDrawerAdapter(getActivity(), new NavigationDrawerAdapter.ClickListener() {
@Override
public void onClick(int index) {
selectItem(index);
}
@Override
public boolean onLongClick(final int index) {
Pins.Item item = mAdapter.getItem(index);
Utils.showConfirmDialog(getActivity(), R.string.remove_shortcut,
R.string.confirm_remove_shortcut, item.getDisplay(getActivity()), new CustomDialog.SimpleClickListener() {
@Override
public void onPositive(int which, View view) {
Pins.remove(getActivity(), index);
mAdapter.reload(getActivity());
}
}
);
return false;
}
});
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter.setCheckedPos(mCurrentSelectedPosition);
return mRecyclerView;
}
And this is the fragment_drawer
layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/cover_bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/banner" />
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/cover_bg"
android:background="?drawer_background"
android:scrollbars="vertical" />
</RelativeLayout>
I don't know how it can't cast the RelativeLayout.. Same crash with LinearLayout.
Upvotes: 6
Views: 16823
Reputation: 1007584
mRecyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_drawer, container, false);
Your fragment_drawer
layout does not have a RecyclerView
as its root element. It has a RelativeLayout
as its root element. Hence, inflate()
will be returning the RelativeLayout
, which itself has the RecyclerView
inside of it.
Change your code to:
View drawer = inflater.inflate(R.layout.fragment_drawer, container, false);
mRecyclerView = (RecyclerView) drawer.findViewById(android.R.id.list);
Here, we get the RecyclerView
by finding the @android:id/list
widget inside the inflated layout.
Upvotes: 8