Search code examples
javaandroidandroid-recyclerviewstaggered-gridview

StaggeredGridView changing item sizes on scroll


I have run into this problem

Am using a staggered grid view and it has a combination of two columns and single columns..Something like this

enter image description here

everything works fine, until i scroll up and down a few times and it randomly changes to something like this

enter image description here

A few more scrolls and it ended up like this

enter image description here I have no idea why and its very random. I tried to do a notifyDataSetChanged each time the page is shown, and does'nt seem to do anything

This is the code for my dashboard

public class DashboardStaggered extends Fragment {
    RecyclerView mRecyclerView;
    View v;
    MasonryAdapter adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("MASONRY", "onCreateView");
        super.onCreate(savedInstanceState);
        if(v==null) {
            Log.d("MASONRY", "v is NULL recreating");
            v = inflater.inflate(R.layout.activity_dashboard_staggered, container, false);
            setupRecyclerView();
        }else{
            Log.d("MASONRY", "v is NOT NULL");

        }

        return v;
    }

    private void setupRecyclerView(){
        mRecyclerView = (RecyclerView) v.findViewById(R.id.masonry_grid);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        adapter = new MasonryAdapter(getActivity(),this);
        mRecyclerView.setAdapter(adapter);
        SpacesItemDecoration decoration = new SpacesItemDecoration(12);
        mRecyclerView.addItemDecoration(decoration);
        adapter.notifyDataSetChanged();

    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("MASONRY", "onResume");
        if(mRecyclerView==null) {
            setupRecyclerView();
        }



    }
    @Override
    public void onPause() {
        super.onPause();
        Log.d("MASONRY", "onPause");

    }

}

If needed i could post the adapter too. Any suggestions are highly appreciated folks.

Adapter code here(don't want to make the post messy) http://pastebin.com/QkZbjjp1

Trimmed code http://pastebin.com/Hgsji1RG


Solution

  • As jason mentioned in the comments, it was a blunder in itemgetviewtype, logical error more than anything else. But lesson learnt, the updated code for getItemViewType is

    @Override
        public int getItemViewType(int position) {
            // Return type based on position
            return tileDefinitions.get(position).getTileType();
        }
    

    Thanks everyone for pointing it out.