GridLayoutManager - how to auto fit columns?

后端 未结 8 1974
野性不改
野性不改 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:30

    Use this function, and put margins for cell layout in XML instead using decoration.

    public int getNumberOfColumns() {
            View view = View.inflate(this, R.layout.row_layout, null);
            view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int width = view.getMeasuredWidth();
            int count = getResources().getDisplayMetrics().widthPixels / width;
            int remaining = getResources().getDisplayMetrics().widthPixels - width * count;
            if (remaining > width - 15)
                count++;
            return count;
        }
    
    0 讨论(0)
  • 2020-11-30 19:35

    A simple Kotlin extension function. Pass the width in DP (same as the overall width in the item xml)

    /**
     * @param columnWidth - in dp
     */
    fun RecyclerView.autoFitColumns(columnWidth: Int) {
        val displayMetrics = this.context.resources.displayMetrics
        val noOfColumns = ((displayMetrics.widthPixels / displayMetrics.density) / columnWidth).toInt()
        this.layoutManager = GridLayoutManager(this.context, noOfColumns)
    }
    

    Call it like every other extension...

    myRecyclerView.autoFitColumns(200)
    
    0 讨论(0)
提交回复
热议问题