1

I have this code, which integrates a RecyclerView within a Fragment, but this line:

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager (this, 3);

Gives me an error, it tells me that:

GridLayoutManager (android.content.Context, int) in GridLayoutManager can not be applied to (com.example.julianrc1.petracecitm.PerdidosGaleria_Fragment,int)

And I don't know why, any idea?

Here's the code I'm using:

package com.example.julianrc1.petracecitm;

import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class PerdidosGaleria_Fragment extends Fragment {

    private RecyclerView recyclerView;
    private AnunciosAdapter adapter;
    private List<Anuncio> anuncioList;

    public PerdidosGaleria_Fragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_perdidosgaleria, container, false);
        Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

        //initCollapsingToolbar();

        recyclerView = (RecyclerView)  rootView.findViewById(R.id.content_main);

        anuncioList = new ArrayList<>();
        adapter = new AnunciosAdapter(this, anuncioList);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 3);//columnas que quieres por filas
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        prepareAlbums();

        try {
          //  Glide.with(this).load(R.drawable.cover).into((ImageView) rootView.findViewById(R.id.backdrop));
        } catch (Exception e) {
            e.printStackTrace();
        }


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_perdidosgaleria, container, false);
    }
/*
    private void initCollapsingToolbar() {

        final CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle(" ");
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
        appBarLayout.setExpanded(true);

        // hiding & showing the title when toolbar expanded & collapsed
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (scrollRange == -1) {
                    scrollRange = appBarLayout.getTotalScrollRange();
                }
                if (scrollRange + verticalOffset == 0) {
                    collapsingToolbar.setTitle(getString(R.string.app_name));
                    isShow = true;
                } else if (isShow) {
                    collapsingToolbar.setTitle(" ");
                    isShow = false;
                }
            }
        });
    }
*/
    /**
     * Adding few albums for testing
     */
    private void prepareAlbums() {
        int[] covers = new int[]{
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon,
                R.drawable.icon};

        Anuncio a = new Anuncio("True Romance", 13, covers[0]);
        anuncioList.add(a);

        a = new  Anuncio("Xscpae", 8, covers[1]);
        anuncioList.add(a);

        a = new  Anuncio("Maroon 5", 11, covers[2]);
        anuncioList.add(a);

        a = new  Anuncio("Born to Die", 12, covers[3]);
        anuncioList.add(a);

        a = new  Anuncio("Honeymoon", 14, covers[4]);
        anuncioList.add(a);

        a = new  Anuncio("I Need a Doctor", 1, covers[5]);
        anuncioList.add(a);

        a = new  Anuncio("Loud", 11, covers[6]);
        anuncioList.add(a);

        a = new  Anuncio("Legend", 14, covers[7]);
        anuncioList.add(a);

        a = new  Anuncio("Hello", 11, covers[8]);
        anuncioList.add(a);

        a = new  Anuncio("Greatest Hits", 17, covers[9]);
        anuncioList.add(a);

        adapter.notifyDataSetChanged();
    }

    /**
     * RecyclerView item decoration - give equal margin around grid item
     */
    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }

    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }
}
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
Fairy Band
  • 45
  • 1
  • 6

5 Answers5

2

Change

new GridLayoutManager(this, 3)

to:

new GridLayoutManager(getActivity(), 3)
S.Elaiotrivaris
  • 206
  • 2
  • 7
2

Change this to getActivity() , because you are using recyclerView in Fragment.

  • this is the context of Activity.
  • getActivity() is the context of Fragment.

Code :

  RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 3); 

to

 RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3); 
Abhishek kumar
  • 4,347
  • 8
  • 29
  • 44
2

You have to change the following:- You cant use fragment instead of context as fragment doesnt extend context. But Activity extends context.

You can use getActivity(), which returns the activity associated with a fragment. The activity is a context (since Activity extends Context).

  RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 3);

To

 RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
lib4backer
  • 3,337
  • 3
  • 18
  • 16
2

the main reason that Fragment class do not extentd Context Class

java.lang.Object
   ↳    android.app.Fragment

and the Activity Class have a Context

java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper
               ↳    android.app.Activity

that why when you use this it will work in activity and in fragment not

then you need to use getActivity() in fragment instead of this to pass context

Ali Asadi
  • 987
  • 10
  • 13
0

Please use getActivity() in new GridLayoutManager(getActivity(), 3) instead of new GridLayoutManager(this, 3)

Reason: GridLayoutManager(Context context, int spanCount) requires an instance of a Context type in the first argument and a span count as the second argument.

When you are using this, you are passing a Fragment instance instead, which is not the right argument to pass.

Happy to help.

iamgopal
  • 634
  • 5
  • 12