본문 바로가기
안드로이드

[Android Studio] flexbox Layout 사용하기 (코틀린)

by 개발_블로그 2023. 9. 14.
반응형

리사이클러뷰를 만들다 보면 GridLayoutManager 를 사용해서 그리드뷰를 만들때가 있다.

이 때 아이템 뷰의 width 와 height 을 고정값으로 두지 않고 flexible 하게 사용해야 할 때가 있는데

사용하면 좋은 코드이다.

 

 

구글 github https://github.com/google/flexbox-layout

 

GitHub - google/flexbox-layout: Flexbox for Android

Flexbox for Android . Contribute to google/flexbox-layout development by creating an account on GitHub.

github.com

 

 

gradle 추가.

 

implementation 'com.google.android.flexbox:flexbox:3.0.0'

 

 

사용법은 일반 RecyclerView 를 사용하는 것과 별반 다르지 않다. 

 

item

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <import type="android.view.View" />

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/size08"
        android:layout_marginTop="@dimen/size08"
        android:background="@drawable/ripple_bg_roundbox_line_gray03_18_dp"
        android:paddingHorizontal="@dimen/size16"
        android:paddingVertical="@dimen/size08">

        <TextView
            android:id="@+id/textView"
            style="@style/fs_body_1_md"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="@color/grayscale_09"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 

 

activity_main

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="@dimen/match_constraint"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/size18"
    android:nestedScrollingEnabled="false"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>

 

 

Adapter 는 일반 RecyclerView와 마찬가지 임으로 생략하겠습니다.

 

private val adapter =
    Adapter(lifecycleOwner, clickUtil, eventListener)

 

리사이클러뷰 설정.

binding.recyclerView.apply {
    val flexboxLayoutManager = FlexboxLayoutManager(binding.root.context).apply {
        flexDirection = FlexDirection.ROW
        flexWrap = FlexWrap.WRAP
    }
    layoutManager = flexboxLayoutManager

    adapter = this.adapter
}

 

FlexboxLayoutManager 를 사용해줘서 리사이클러뷰의 layoutManager 에 set 해준다. 

어렵지 않으니 한 번 해보면 다양한 view 를 만들 수 있을 것 같다. 

 

 

반응형