이번 시간에는 Flexbox Layout 을 사용해보도록 하겠습니다.
Flexbox Layout 는 웹의 css 에서 사용하던 flexbox 를 안드로이드에서 비슷하게 구현한 라이브러리인데요.
예를들면, 좌측 정렬로 뷰들이 쌓이다가 우측끝에 닿았을때 다음 줄로 넘어가야하는 상황이 생길 수 있는데 그럴때 사용할 수 있어요.
google 에서 만들었고, 아파치 라이센스로 사용하시는데 큰 문제는 없을 것으로 보여요.
https://github.com/google/flexbox-layout
라이브러리를 사용하기 위해서 모듈 수준의 build.gradle 파일에 의존성을 추가해주세요.
2021/11/19 기준 최신 버전은 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 androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.flexbox.FlexboxLayoutManager;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
recyclerView.setLayoutManager(flexboxLayoutManager);
String 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";
String[] wordList = wordString.split(",");
RecyclerView.Adapter<RecyclerView.ViewHolder> recyclerViewAdapter = new RecyclerView.Adapter<RecyclerView.ViewHolder>() {
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, parent, false);
return new RecyclerView.ViewHolder(itemView) {
};
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Button button = holder.itemView.findViewById(R.id.button);
button.setText(wordList[position]);
}
@Override
public int getItemCount() {
return wordList.length;
}
};
recyclerView.setAdapter(recyclerViewAdapter);
}
}
단어 출처 :
https://www.ef.co.kr/english-world/english-vocabulary/top-1000-words/
메인 화면에 리사이클러뷰 하나를 두고 액티에서 레이아웃 매니저와 어뎁터를 설정해주었습니다.
레이아웃 메니저로 FlexboxLayoutManager 매니저를 사용했습니다.
자식뷰를 가운데로 정렬하고 싶으면 flexboxLayoutManager 의 setJustifyContent 메소드를 사용해주세요.
FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
flexboxLayoutManager.setJustifyContent(JustifyContent.CENTER);
이외 다른 속성들은 공식 홈페이지를 확인하시면 됩니다.
마지막으로 실행 영상입니다.
'안드로이드 자바' 카테고리의 다른 글
[JAVA][Android] [안드로이드] Volley+를 이용해서 서버에 파일 업로드하기 (0) | 2022.02.11 |
---|---|
[Java][Android] 모션 레이아웃 (0) | 2022.02.07 |
[JAVA][Android]사라지는 AppBar 구현하기 (0) | 2022.02.05 |
[Java][Android] 바인드서비스로 데이터 받기 (0) | 2022.02.02 |
[JAVA][Android] 원형 그래프 만들기 (0) | 2022.01.31 |