apk apk - 23 days ago 8
Android Question

Unable to cast LinearLayoutManager to GridLayoutManager

if (mLayoutManager instanceof GridLayoutManager) {
((GridLayoutManager) mLayoutManager).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
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

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;
}
Comments