0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RecyclerViewで横並びのアイテムをn個見せる方法

0
Posted at

RecyclerViewでアイテムを横並び表示する時に、表示させるアイテム数の制御方法をメモします。

アイテム数を3.2個分表示させ、次のアイテムを少しだけ見せたい時、画面幅から3.2を割り、アイテムの横幅とすればいいです。

val itemWidth = parent.measuredWidth / 3.2f

ですが実際にはアイテム間のマージン、画面左右のマージンを考慮したいので少し工夫します。
今回は以下の条件とします。

  • 画面左右のマージン : 8dp
  • アイテム間のマージン : 4dp
  • 表示数 : 3.2個

実装方法

val height = RecyclerView.LayoutParams.WRAP_CONTENT
val visibleItem = 3.2f
val activityMargin = resources.getDimension(R.dimen.activity_margin) // 8dp
val itemSpacing = resources.getDimension(R.dimen.item_space)         // 4dp

val availableWidth = parent.measuredWidth - activityMargin * 2
val totalSpacing = itemSpacing * (visibleItem - 1)
val itemWidth = (availableWidth - totalSpacing) / visibleItem

view.layoutParams = RecyclerView.LayoutParams(
    itemWidth.toInt(),
    height
)

数値で確認してみます。画面幅が360dpの場合、RecyclerViewの利用可能幅は、

360 - 8 - 8 = 344dp

スペース合計は、

4 × (3.2 - 1) = 8.8dp

したがってアイテム幅は、

(344 - 8.8) / 3.2 = 104.75dp

となります。実際に並べると、

カード幅 × アイテム間のマージン × 画面左右のマージン
104.75 × 3.2 + 4 × 2.2 + 8 × 2 = 360

となり、きれいに3.2個表示できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?