티스토리 뷰

Android의 탭은 네비게이션 위젯이라고 불리기도 하며, 상답 탭과 하단 탭으로 구분한다. 

 

상단 탭의 경우에는 직전 포스팅에서 다뤘던 액션바에 탭 기능을 넣어 보여주는 방법으로 제공되며, 하단 탭은 별도의 위젯으로 제공된다.

 

바로 한번 간단한 탭을 만드는 예제를 확인해보자.


우선, 상단바 레이아웃을 구성하기 위해 activity_main.xml의 파레트에서 appBarLayout 을 끌어와야한다. 

 

AppBarLayout을 가져오면, 대략적인 xml 소스의 태그 구성은 다음과 같이 구성이 된다.

 

<CoordinatorLayout>: AppBarLayout을 감싸는 레이아웃

  <AppBarLayout>: 상단 액션바

     <Toolbar>: 탭 주변에 놓이는 툴바

     </Toolbar>

     <TabLayout>: 각 탭을 나열할 탭 부분

     </TabLayout>

   </AppBarLayout>

</CoordinatorLayout>

 

◎activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?colorPrimaryDark"
                android:elevation="1dp"
                android:theme="@style/ThemeOverlay.AppCompat.Dark">
            <TextView
                    android:id="@+id/titleText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="타이틀"
                    android:textAppearance="@style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title" />

        </androidx.appcompat.widget.Toolbar>

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

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

    <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

    </FrameLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

 

각 탭을 클릭하면 아래 쪽에 화면이 변경되도록 구성할 것이기 때문에, AppBarLayout 하단에 FrameLayout을 추가하여 화면이 들어갈 container를 생성한다.

 

이제 container에 들어갈 화면을 간단하게 아래와 같이 3개 구성한다.

 

◎Fragment1 ~ 3 .xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <Button
            android:text="첫번째"
            android:layout_width="0dp"
            android:layout_height="51dp" android:id="@+id/button"
            app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

 

프래그먼트 레이아웃을 작성하고 바로 inflate까지 해주자.

 

◎Fragment1 ~ 3 .java

package com.example.sampletab;

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) {
        return inflater.inflate(R.layout.fragment1,container, false);
    }
}

 

이제 MainActivity 클래스에서 container에 첫번째 프래그먼트를 설정해준 뒤, TabLayout 객체를 호출하여 각 탭을 설정해주고, 각 탭의 클릭 이벤트까지 구성한다.

 

◎MainActivity.java

package com.example.sampletab;

import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;

    Fragment1 fragment1;
    Fragment2 fragment2;
    Fragment3 fragment3;

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

        toolbar = findViewById(R.id.toolbar);

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

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

        TabLayout tabs = findViewById(R.id.tabs);
        tabs.addTab(tabs.newTab().setText("통화기록"));
        tabs.addTab(tabs.newTab().setText("스팸기록"));
        tabs.addTab(tabs.newTab().setText("연락처"));

        tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                Toast.makeText(getApplicationContext(), "선택된 탭: " + position, Toast.LENGTH_LONG).show();
                
                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) {

            }
        });

    }
}

TabLayout의 Tab 객체는 getPosition() 메서드로 어떤 탭이 선택되었는 지 int값을 반환하기 때문에 이를 이용하여 위와 같이 작성해주면 된다.


 

Comments