탭레이아웃(TabLayout) 사용하기

 


안드로이드 탭레이아웃(TabLayout) : https://material.io/develop/android/components/tab-layout/

 

Tab Layout - Material Components for Android

Tab Layout TabLayout provides a horizontal layout to display tabs. The layout handles interactions for a group of tabs including: scrolling behavior, (swipe) gestures, tab selection, animations, and alignment. The Android Developers site provides detailed

material.io

 

탭레이아웃을 사용하려면 우선 build.gradle에 dependency를 추가시켜줘야 합니다.

implementation 'com.android.support:design:28.0.0'

( ※ 싱크 후 에러가 뜰 경우 Alt + Enter를 통해서 해결해주시면 됩니다. )

 

 

xml 코드

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0xxx"/>
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1xxx"/>
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2xxx"/>
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="3xxx"/>
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="4xxx"/>
        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="5xxx"/>

    </com.google.android.material.tabs.TabLayout>

탭레이아웃 안에 탭아이템을 통해서 탭 설정을 해주시면 됩니다.

 

탭을 많이 만들어서 스크롤이 가능하게 하려면 탭레이아웃 태그 내에 tabMode를 추가시켜주시면 됩니다.

app:tabMode="scrollable"

 

그리고 기타 추가구현 사항은 맨 위에 올린 링크를 통해 들어가시면

아이콘, 백그라운드, 사이즈, 색상 등 사용방법을 확인하실 수 있습니다.

 

 


(+ 탭 Fragment 연결)

 

탭을 클릭했을 때 각각의 탭마다 Fragment연결을 시켜주겠습니다.

우선 activity_main.xml에서 탭레이아웃 밑에 FrameLayout을 생성합니다.

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

RelativeLayout를 사용했으므로 layout_below로 탭레이아웃 아래에 위치하도록 했습니다.

 

 

연결시켜줄 xml과 java파일을 생성합니다.

 

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="20sp"
        android:text="0000"/>

</LinearLayout>

간단하게 xml 파일을 만들어 주고

 

public class Fragment0 extends Fragment {

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

        return view;
    }
}

java 파일도 생성했습니다. 원하는 탭 갯수만큼 생성시켜주시면 됩니다.

 

public class MainActivity extends AppCompatActivity {

    Fragment fragment0, fragment1, fragment2, fragment3;

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

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

        getSupportFragmentManager().beginTransaction().add(R.id.frame, fragment0).commit();

        TabLayout tabs = (TabLayout) findViewById(R.id.tabs);

        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                int position = tab.getPosition();

                Fragment selected = null;
                if(position == 0){

                    selected = fragment0;

                }else if (position == 1){

                    selected = fragment1;

                }else if (position == 2){

                    selected = fragment2;

                }else if (position == 3){

                    selected = fragment3;
                }

                getSupportFragmentManager().beginTransaction().replace(R.id.frame, selected).commit();
            }

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

            }

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

            }
        });
    }
}

MainActivity에서 만든 Fragment들을 선언해주고,

getSupportFragmentManager().beginTransaction().add(R.id.frame, fragment0).commit(); 으로 초기화면을 설정합니다.

그리고 TabLayout의 addOnTabSelectedListener에 onTabSelected메서드를 이용해서

해당탭을 클릭했을 때 getPosition() 값을 이용해 프래그먼트 전환시켜줍니다.


+ Recent posts