Search code examples
androidkotlinandroid-recyclerviewgridlayoutmanager

Is it possible to adjust the number of rows and columns of recyclerview using gridLayoutManager according to the screen width?


In a course of developing an Android app, something happened to show the user a list of items. If you are looking at a mobile phone vertically, the number of rows are not limited, but if you are looking horizontally, you want to create a function that allows you to adjust the number of columns according to the width. This is the code I am currently using.

class MainActivity : AppCompatActivity() {
    var array: ArrayList<String>? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        ...
        recyclerView.layoutManager = GirdLayoutManager(this, 2)
        recyclerView.setHasFixedSize(true)
        recyclerView.adapter = MyAdapter(array!!)
    }
}

Since the value of spanCount is set to 2, of course, I know that the number of columns is set to 2. I just want the width of the itemView I want to show is properly adjusted according to the mobile width. Is there any solution?

If you need a custom GridLayout manager, how do you make it?


Solution

  • You could add integer resource file into res/values that holds different variants of the spanCount value that you want to vary for different screen widths.

    Right Click on on res/values > New > Values Resource File > Pick a name for the file > select Screen Width qualifier and set the screen width value in dp

    enter image description here

    Then add an integer value

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

    Repeat this for different screen widths you want the span vary in. And of course create the default resource file that match any other screen width you didn't mention (that has no qualifiers identified.)

    And to build the recyclerView span get that resource, and it automatically takes the appropriate resource value according to the screen width:

    recyclerView.layoutManager = GirdLayoutManager(this, resources.getInteger(R.integer.span))