GridLayoutManager - how to auto fit columns?

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

提交回复
热议问题