Android

[Android] TabLayout 만들기

도우 2024. 2. 7. 10:57
728x90

1. Gradle 설정: 필요한 라이브러리를 프로젝트의 build.gradle 파일에 추가합니다.

 

Gradle Scripts 안에 있는 build.gradle.kts (Module : app)에 추가합니다. 

dependencies{
    implementation("androidx.viewpager2:viewpager2:1.0.0")
    implementation("com.google.android.material:material:1.2.1")
    implementation("androidx.recyclerview:recyclerview:1.1.0")
    }

 

 

2. Layout 작성

 

TabLayout을 작성합니다.

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

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="3" />

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

 

 

탭이 많아서 스크롤 해야할 경우 다음 속성을 추가합니다.

app:tabMode="scrollable"

 

 

3. FrameLayout 작성 : 프래그먼트 컨테이너

 

프래그먼트를 동적으로 교체하기 위해 TabLayout 아래에 작성합니다.

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

 

※ FrameLayout의 필요성

ViewPager2를 사용하여 탭 간의 페이지 전환을 구현할 경우, 각 탭의 컨텐츠는 ViewPager2 내의 프래그먼트로 관리되므로 별도의 FrameLayout을 프래그먼트 컨테이너로 사용할 필요는 없다.

 

ViewPager2를 사용한 경우는 이 글을 참고해주세요

https://ehdnsdlek.tistory.com/4

 

[Android] TabLayout에 ViewPager2 사용하기

TabLayout에 프래그먼트 컨테이너로써 FrameLayout을 사용한다면, 사용자가 직접 스와이프를 할 수 없고 프래그먼트 간의 네이게이션이 더 복잡해질 수 있다. ViewPager - 내장된 스와이프 네비게이션 -

ehdnsdlek.tistory.com

 

 

4. Fragment 작성

 

탭 개수만큼 Fragment 파일을  만들어 주자.

// Fragment1.java
public class Fragment1 extends Fragment {

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

        return firstView;
    }
}

 

// fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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="1111"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

5. Fragment 연결

 

MainActivity의 TabLayout에 Fragment1, Fragment2, Fragment3을 연결합니다.

public class MainActivity extends AppCompatActivity {

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

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

        // 초기 화면 설정
        getSupportFragmentManager().beginTransaction().add(R.id.frame, fragment1).commit();

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

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

            }

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

            }

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

            }
        });

    }
}

 

 

6. 화면 전환 구성

 

onTabSelected 메소드 안에 사용자 선택에 따라 보여줄 프래그먼트를 결정합니다.

@Override
public void onTabSelected(TabLayout.Tab tab) {
    int position = tab.getPosition();
    Fragment selectedFragment = null;
    switch (position) {
        case 0:
            selectedFragment = fragment1;
            break;
        case 1:
            selectedFragment = fragment2;
            break;
        case 2:
            selectedFragment = fragment3;
            break;
    }
    // 안드로이드 앱 내에서 동적으로 프래그먼트를 교체하는 역할
    if (selectedFragment != null) {
        getSupportFragmentManager().beginTransaction().replace(R.id.frame, selectedFragment).commit();
    }
}

 

 

7. 프래그먼트의 화면 구성

 

// Fragment1.java
public class Fragment1 extends Fragment {

    public Fragment1() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);
    }
}

 

 

 

<결과>

 

 

 

 

※ 피드백 환영합니다

728x90