apk apk - 1 year ago 108
Android Question

Unable to cast LinearLayoutManager to GridLayoutManager

if (mLayoutManager instanceof GridLayoutManager) {
((GridLayoutManager) mLayoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
public int getSpanSize(int position) {
return listResultAdapter.isHeaderOrFooter(position) ? ((GridLayoutManager) mLayoutManager).getSpanCount() : 1;

Above code is crashing saying java.lang.ClassCastException: android.support.v7.widget.LinearLayoutManager cannot be cast to android.support.v7.widget.GridLayoutManager

I figured out below line is causing crash

((GridLayoutManager) mLayoutManager).getSpanCount()

what can be the solution to avoid crash

mLayoutManager is declared as LinearLayoutManager

Answer Source

You should also do the class check inside getSpanSize:

public int getSpanSize(int position) {
     return mLayoutManager instanceof GridLayoutManager && listResultAdapter.isHeaderOrFooter(position) 
             ? ((GridLayoutManager) mLayoutManager).getSpanCount() : 1;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download