Sobes.tech
Middle

How to change the number of columns in RecyclerView so that in portrait orientation one column is displayed, and when switching to landscape - two or more columns?

sobes.tech AI

Answer from AI

You can use GridLayoutManager.

To change the number of columns depending on the screen orientation, you should:

  1. Get the current device orientation.
  2. Depending on the orientation, create a GridLayoutManager with the required number of columns and set it for the RecyclerView.

Example:

// In the activity or fragment where RecyclerView is used
override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    updateColumnCount(newConfig.orientation)
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // ... initialize RecyclerView ...

    updateColumnCount(resources.configuration.orientation)
}

private fun updateColumnCount(orientation: Int) {
    val spanCount = if (orientation == Configuration.ORIENTATION_PORTRAIT) {
        1 // One column in portrait orientation
    } else {
        2 // Two columns in landscape orientation
        // You can use other values, e.g., 3, 4, etc.
    }

    recyclerView.layoutManager = GridLayoutManager(this, spanCount)
}

You can also define the number of columns in resource files (dimens.xml) for different orientations:

Create res/values/dimens.xml:

<resources>
    <integer name="grid_span_count">1</integer>
</resources>

Create res/values-land or res/values-sw600dp-land (for tablets) dimens.xml:

<resources>
    <integer name="grid_span_count">2</integer>
</resources>

And then use this resource in your code:

recyclerView.layoutManager = GridLayoutManager(this, resources.getInteger(R.integer.grid_span_count))

This approach is more flexible, as it allows easy changes to the number of columns without modifying the code.