Search code examples
androidandroid-recyclerviewandroid-screen-support

can I make my recycler view responsive with respect to screen sizes?


This is my code, Where I am displaying 2 items per row.

extends Fragment {

private RecyclerView recyclerView;
private AlbumsAdapter adapter;
private List<Album> albumList;
protected View view;
private FloatingActionButton fab;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.fragment_ebooks, container, false);
    fab = (FloatingActionButton) view.findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), ProductsActivity.class);
            startActivity(intent);
        }
    });
    initCollapsingToolbar();

    recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);

    albumList = new ArrayList<>();
    adapter = new AlbumsAdapter(getActivity(), albumList);

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
    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) view.findViewById(R.id.backdrop));
    } catch (Exception e) {
        e.printStackTrace();
    }
return view;
}


/**
 * Initializing collapsing toolbar
 * Will show and hide the toolbar title on scroll
 */
private void initCollapsingToolbar() {
    final CollapsingToolbarLayout collapsingToolbar =
            (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
    collapsingToolbar.setTitle(" ");
    AppBarLayout appBarLayout = (AppBarLayout) view.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.album1,
            R.drawable.album2,
            R.drawable.album3,
            R.drawable.album4,
            R.drawable.album5,
            R.drawable.album6,
            R.drawable.album7,
            R.drawable.album1,
            R.drawable.album2,
            R.drawable.album3,
            R.drawable.album4};

    Album a = new Album("Management..", "Donald", covers[0]);
    albumList.add(a);

    a = new Album("Officers search", "John.A", covers[1]);
    albumList.add(a);

    a = new Album("Court Security", "Carter", covers[2]);
    albumList.add(a);

    a = new Album("Officer DUI", "John", covers[3]);
    albumList.add(a);

    a = new Album("Criminal Evedence", "Larry", covers[4]);
    albumList.add(a);

    a = new Album("Criminal Procedure", "Larry", covers[5]);
    albumList.add(a);

    a = new Album("Officers DUI", "John", covers[6]);
    albumList.add(a);

    a = new Album("K9 Officers..", "Ken", covers[7]);
    albumList.add(a);

    a = new Album("Officers search", "John", covers[8]);
    albumList.add(a);

    a = new Album("Tactical Spanish", "Larry", covers[9]);
    albumList.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()));
}

Using this line of code I am displaying 2 items in a row.

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);

I want to make my recycler view responsive so that I can use my app in different screen sizes of android.

I had done this using card view where I had placed card views in a linear layout where the number of cards are fixed I had done that by creating different layouts. Now I want to change it in recycler view where my items can be increased dynamically.

Please help me to make my recycler view responsive dynmically.


Solution

  • Easiest way to solve your problem is to define a resource integer that you access from the code. So for example if you want to have 2 rows on normal screens you add the following line to integers.xml in the res\values folder in res:

    <integer name="number_of_grid_items">2</integer>
    

    And if you want to have 3 items on xxxhdpi screens you add the following line to the integers.xml file in the res\values-xxxhdpi folder:

    <integer name="number_of_grid_items">3</integer>
    

    If any of those files don't exist yet, just create them that they look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <integer name="number_of_grid_items">2</integer>
    </resources>
    

    To access those resources within you code, just change the line where you create the GridLayoutManager to:

    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), getActivity().getResources().getInteger(R.integer.number_of_grid_items));
    

    Hope that helps and please let me know if you have further questions..