Java – Unable to parse setSpanSizeLookup for gridviewlayoutmanager

Unable to parse setSpanSizeLookup for gridviewlayoutmanager… here is a solution to the problem.

Unable to parse setSpanSizeLookup for gridviewlayoutmanager

I’m trying to set a custom span size based on the type of object I want to display, but when I get the following error in the IDE:

cannot resolve method
SetSpanSizeLookup(anonymous.android.support.v7.widget.GridLayoutManager.SpanSizeLookup)

I don’t understand why this is, because according to googleThis seems to be a supported method

mLayoutManager = new GridLayoutManager(this,3);

mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch(mAdapter.getItemViewType(position)){
            case MyAdapter.TYPE_HEADER:
                return 2;
            case MyAdapter.TYPE_ITEM:
                return 1;
            default:
                return -1;
        }
    }
});

Solution

Your mLayoutManager object must be of type GridLayoutManager.

If you need it to be an abstract type LayoutManager (although I can’t imagine that case), you can convert it as follows:

((GridLayoutManager) mLayoutManager).setSpanSizeLookup(...)

Related Problems and Solutions