How to make columns responsive with Gridlayoutmanager?

Asked

Viewed 197 times

0

In the precise case that when you are in Portrait display a number of columns that complete the width of the screen and when in Landscape the items in recyclerview are presented in a number of columns proportional to the new width, preventing it to be deformed the proportions of cardviews.

  • Add the question to the layout of Recyclerview items.

1 answer

0

Use the getRotation():

WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

if (manager != null) {
    Display display = manager.getDefaultDisplay();
    int rotation = display.getRotation();

    if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
        //em LADNSCAPE atribuimos uma quantidade de colunas maior a sua recycler view
        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
    } else {
        //em PORTRAIT uma quantidade menor
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    }
}

You can run this code on your onCreate, when configuring your UI.

Link to the class documentation: Display

  • And in case I implement my recyclerview in a Fragment, I would use that code, or I would have another way in that case?

  • The only difference is that you would need to allocate this code to onCreateView of your Fragment. Works normally.

  • Thanks for the help! And sorry for the delay in thanking you. It worked right here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.