본문 바로가기
안드로이드 코틀린

[Kotlin][Android] Flexbox Layout 사용해보기

by teamnova 2022. 3. 8.

java 버전은 https://stickode.tistory.com/391 에서 확인해주세요.

 

 

이번 시간에는 Flexbox Layout 을 사용해보도록 하겠습니다.

 

Flexbox Layout 는 웹의 css 에서 사용하던 flexbox 를 안드로이드에서 비슷하게 구현한 라이브러리인데요.

 

예를들면, 좌측 정렬로 뷰들이 쌓이다가 우측끝에 닿았을때 다음 줄로 넘어가야하는 상황이 생길 수 있는데 그럴때 사용할 수 있어요.

 

google 에서 만들었고, 아파치 라이센스로 사용하시는데 큰 문제 없을 것으로 보여요.

 

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

 

라이브러리를 사용하기 위해서 모듈 수준의 build.gradle 파일에 의존성을 추가해주세요.

 

2021/11/28 기준 최신 버전은 3.0.0 입니다.

dependencies {
    implementation 'com.google.android.flexbox:flexbox:3.0.0'
}

 

일반적인 사용법은 xml 에서 다른 레이아웃 사용하듯이 선언하신 다음 하위 뷰로 다른 뷰들을 넣어주시면 됩니다.

 

하나 추가해주실 속성은 app:flexWrap 입니다.

 

wrap 으로 설정해주시면 자식뷰가 화면을 넘어갈때 다음 줄로 이동하게 됩니다.

 

아래 코드를 붙어넣으신 다음 버튼들의 크기를 조절해보시면 이해가 쉽습니다.

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.flexbox.FlexboxLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    app:flexWrap="wrap"
    >

    <Button
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:text="안녕하세요"
        android:layout_marginHorizontal="10dp"
        />


    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="길이"
        android:layout_marginHorizontal="20dp"
        />


    <Button
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:text="안녕하세요"
        android:layout_marginHorizontal="20dp"
        />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="안녕하세요"
        android:layout_marginHorizontal="20dp"
        />

</com.google.android.flexbox.FlexboxLayout>

 

이제 어떤 기능을 하는지 알아보았으니 다음으로 리사이클러뷰의 레이아웃 매니저로 사용하는 방법을 알아보도록 하겠습니다.

 

지금 구현했던 정렬 기능을 리사이클러뷰에서도 사용할 수 있습니다.

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

item.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="4dp"
    />

MainActivity.java


import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent


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

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        val flexboxLayoutManager = FlexboxLayoutManager(this)
        flexboxLayoutManager.justifyContent = JustifyContent.CENTER
        recyclerView.layoutManager = flexboxLayoutManager

        val wordString = "ability, able, about, above, accept, according, account, across, act, action, activity, actually, add, address, administration, admit, adult, affect, after, again, against, age, agency, agent, ago, agree, agreement, ahead, air, all, allow, almost, alone, along, already, also, although, always, American, among, amount, analysis, and, animal, another, answer, any, anyone, anything, appear, apply, approach, area, argue, arm, around, arrive, art, article, artist, as, ask, assume, at, attack, attention, attorney, audience, author, authority, available, avoid, away, baby, back, bad, bag, ball, bank, bar, base, be, beat, beautiful, because, become, bed, before, begin, behavior, behind, believe, benefit, best, better, between, beyond, big, bill, billion, bit, black, blood, blue, board, body, book, born, both, box, boy, break, bring, brother, budget, build, building, business, but, buy, by, call, camera, campaign, can, cancer, candidate, capital, car, card, care, career, carry, case, catch, cause, cell, center, central, century, certain, certainly, chair, challenge, chance, change, character, charge, check, child, choice, choose, church, citizen, city, civil, claim, class, clear, clearly, close, coach, cold, collection, college, color, come, commercial, common, community, company, compare, computer, concern, condition, conference, Congress, consider, consumer, contain, continue, control, cost, could, country, couple, course, court, cover, create, crime, cultural, culture, cup, current, customer, cut, dark, data, daughter, day, dead, deal, death, debate, decade, decide, decision, deep, defense, degree, Democrat, democratic, describe, design, despite, detail, determine, develop, development, die, difference, different, difficult, dinner, direction, director, discover, discuss, discussion, disease, do, doctor, dog, door, down, draw, dream, drive, drop, drug, during, each, early, east, easy, eat, economic, economy, edge, education, effect, effort, eight, either, election, else, employee, end, energy, enjoy, enough, enter, entire, environment, environmental, especially, establish, even, evening, event, ever, every, everybody, everyone, everything, evidence, exactly, example, executive, exist, expect, experience, expert, explain, eye, face, fact, factor, fail, fall, family, far, fast, father, fear, federal, feel, feeling, few, field, fight, figure, fill, film, final, finally, financial, find, fine, finger, finish, fire, firm, first, fish, five, floor, fly, focus, follow, food, foot, for, force, foreign, forget, form, former, forward, four, free, friend, from, front, full, fund, future, game, garden, gas, general, generation, get, girl, give, glass, go, goal, good, government, great, green, ground, group, grow, growth, guess, gun, guy, hair, half, hand, hang, happen, happy, hard, have, he, head, health, hear, heart, heat, heavy, help, her, here, herself, high, him, himself, his, history, hit, hold, home, hope, hospital, hot, hotel, hour, house, how, however, huge, human, hundred, husband, I, idea, identify, if, image, imagine, impact, important, improve, in, include, including, increase, indeed, indicate, individual, industry, information, inside, instead, institution, interest, interesting, international, interview, into, investment, involve, issue, it, item, its, itself, job, join, just, keep, key, kid, kill, kind, kitchen, know, knowledge, land, language, large, last, late, later, laugh, law, lawyer, lay, lead, leader, learn, least, leave, left, leg, legal, less, let, letter, level, lie, life, light, like, likely, line, list, listen, little, live, local, long, look, lose, loss, lot, love, low, machine, magazine, main, maintain, major, majority, make, man, manage, management, manager, many, market, marriage, material, matter, may, maybe, me, mean, measure, media, medical, meet, meeting, member, memory, mention, message, method, middle, might, military, million, mind, minute, miss, mission, model, modern, moment, money, month, more, morning, most, mother, mouth, move, movement, movie, Mr, Mrs, much"
        val wordList = wordString.split(",").toTypedArray()

        recyclerView.adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int ): RecyclerView.ViewHolder {
                val itemView = LayoutInflater.from(this@MainActivity).inflate(R.layout.item, parent, false)
                return object : RecyclerView.ViewHolder(itemView) {}
            }

            override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
                val button = holder.itemView.findViewById<Button>(R.id.button)
                button.text = wordList[position]
            }

            override fun getItemCount(): Int {
                return wordList.size
            }
        }
    }
}

단어 출처 :

https://www.ef.co.kr/english-world/english-vocabulary/top-1000-words/

 

https://www.ef.co.kr/english-world/english-vocabulary/top-1000-words/

 

www.ef.co.kr

 

메인 화면에 리사이클러뷰 하나를 두고 액티에서 레이아웃 매니저와 어뎁터를 설정해주었습니다.

 

레이아웃 메니저로 FlexboxLayoutManager 매니저를 사용했습니다.

 

자식뷰를 가운데로 정렬하고 싶으면 flexboxLayoutManager 의 setJustifyContent 메소드를 사용해주세요.

val flexboxLayoutManager = FlexboxLayoutManager(this)
flexboxLayoutManager.justifyContent = JustifyContent.CENTER

이외 다른 속성들은 공식 홈페이지를 확인해주세요.

 

 

마지막으로 실행 영상입니다.