GridLayoutManager - how to auto fit columns?

后端 未结 8 2061
野性不改
野性不改 2020-11-30 18:30

I have a RecyclerView with a GridLayoutManager that displays Card Views. I want the cards to rearrange according to the screen size (the Google Play app does this kind of th

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 19:21

    You can calculate available number of columns, given a desired column width, and load the image as calculated. Define a static funtion to calculate as:

    public class Utility {
        public static int calculateNoOfColumns(Context context, float columnWidthDp) { // For example columnWidthdp=180
            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
            float screenWidthDp = displayMetrics.widthPixels / displayMetrics.density;
            int noOfColumns = (int) (screenWidthDp / columnWidthDp + 0.5); // +0.5 for correct rounding to int.
            return noOfColumns;
        }
    }
    

    And then when using it in the activity or fragment you can do like this :

    int mNoOfColumns = Utility.calculateNoOfColumns(getApplicationContext());
    
    ............
    mGridLayoutManager = new GridLayoutManager(this, mNoOfColumns);
    

提交回复
热议问题