본문 바로가기
Android/Concepts

TabLayout 사용법

by JuHy_ 2020. 4. 14.

TabLayout의 구성

Tab은 크게 Tab 버튼이 위치한 TabLayout과 화면이 바뀌는 아래쪽의 FrameLayout으로 구성된다.

Tab 버튼을 눌렀을 때 아래쪽 부분화면이 바뀌어야 하므로 주로 FrameLayout 안에 Fragment를 넣어 구현한다.

 

사용법

일단 TabLayout을 사용하려면 외부 라이브러리를 dependency에 추가해주어야 한다.

먼저 Project Explorer에서 Gradle Scripts - build.gradle(Module: app)을 클릭해 들어간다.

그리고 dependencies 괄호 안에 다음을 추가한다.

 

// ~ API 28
implementation 'com.android.support:design:27.1.0'

// API 29 ~
implementation 'com.google.android.material:material:1.1.0'

API 28(Pie) 버전까지는 support 라이브러리의 design을 추가하고,

API 29(Q) 버전부터는 material 라이브러리를 추가한다. (androidx로 바뀌면서 support 라이브러리 사용 X)

 

이 글은 API 29(Q) 버전에 맞춰 구현하였다.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@android:color/holo_blue_bright">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display 1"
        android:textSize="40sp"/>

</LinearLayout>
package com.juhy.myapplication;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment1 extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);

        return rootView;
    }
}

먼저 위와 같은 형태로 fragment를 3개 만들어준다. 화면을 구분하기 위해 3개의 배경색은 다르게 하였다.

 

fragment에 대한 자세한 설명은 아래 게시글 참조.

https://ju-hy.tistory.com/52

 

Fragment 사용법

Fragment란? 앱을 개발하다 보면 하나의 액티비티 안에 부분적인 화면을 추가하고 싶을 때가 있다. 특히 액티비티 안에 여러 부분 화면이 전환되게 만들 때 이를 액티비티로 구현하면 앱이 무거워지고 복잡해진다...

ju-hy.tistory.com

 

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

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="1dp"
        android:background="@android:color/background_light"
        app:tabMode="fixed"
        app:tabGravity="fill"
        app:tabTextColor="@color/colorPrimary"
        app:tabSelectedTextColor="@color/colorAccent" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_below="@id/tabs"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    </FrameLayout>

</RelativeLayout>

그 다음 구현할 액티비티의 레이아웃 파일에 TabLayout 하나와 FrameLayout 하나를 추가한다.

 

package com.juhy.myapplication;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends FragmentActivity {

    TabLayout tabs;

    Fragment1 fragment1;
    Fragment2 fragment2;
    Fragment3 fragment3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();

        getSupportFragmentManager().beginTransaction().add(R.id.container, fragment1).commit();

        tabs = findViewById(R.id.tabs);
        tabs.addTab(tabs.newTab().setText("친구"));
        tabs.addTab(tabs.newTab().setText("채팅"));
        tabs.addTab(tabs.newTab().setText("더보기"));

        tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                Fragment selected = null;
                if(position == 0)
                    selected = fragment1;
                else if(position == 1)
                    selected = fragment2;
                else if(position == 2)
                    selected = fragment3;
                getSupportFragmentManager().beginTransaction().replace(R.id.container, selected).commit();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

}

Activity에서는 먼저 fragment를 사용하므로 FragmentActivity를 상속받도록 바꿔준다.

그리고 만들었던 3개의 fragment 객체를 생성하고, FrameLayout에 fragment 하나를 일단 띄워주었다.

 

다음으로 TabLayout을 불러와 addTab() 함수를 통해 탭을 3개 추가해주었다.

그리고 TabLayout에 OnTabSelectedListener를 추가하여 Tab 버튼 클릭 시 fragment가 바뀌도록 구현하였다.

tab.getPosition() 함수를 통해 클릭된 Tab의 위치를 받아와 해당 위치에 맞는 fragment로 replace 해주면 된다.

 

 

실행 후 각 Tab 버튼을 클릭해보면 정상적으로 아래쪽의 fragment가 바뀌는 것을 볼 수 있다.

 

 

Reference

[부스트코스]안드로이드 프로그래밍

https://www.edwith.org/boostcourse-android

'Android > Concepts' 카테고리의 다른 글

ViewPager에 TitleStrip/TabStrip 추가하기  (0) 2020.04.14
ViewPager 사용법  (1) 2020.04.14
ActionBar에 Menu 추가하기  (0) 2020.04.13
Fragment 사용법  (0) 2020.04.09
Permission 획득하기  (0) 2020.04.04