Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 TabHost 사용법, 단계별 예제로 쉽게 배우기

안드로이드 TabHost란 무엇인가?

예제를 시작하기 전에 안드로이드에서 TabHost가 어떤 역할을 하는지 먼저 이해해 보겠습니다. TabHost는 여러 개의 탭을 담는 컨테이너 역할을 하는 위젯입니다. 각 탭에는 프로젝트 요구 사항에 따라 Fragment 또는 Activity가 연결될 수 있으며, 사용자는 탭을 좌우로 스크롤하며 손쉽게 화면을 전환할 수 있습니다.

이 글에서는 실제 예제 코드를 통해 안드로이드에서 TabHost를 구현하고 활용하는 방법을 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤, 메뉴에서 File ⇒ New Project를 선택하여 새 프로젝트를 만듭니다. 프로젝트 생성에 필요한 모든 세부 정보를 입력하면 기본 설정이 완료됩니다.

2단계: 레이아웃 파일 작성

다음 코드를 res/layout/activity_main.xml 파일에 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <TabHost android:id="@+id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <TabWidget android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
            <FrameLayout android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">
                <LinearLayout
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <Button
                        android:id="@+id/button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="tab1" />
                </LinearLayout>
                <LinearLayout
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <Button
                        android:id="@+id/button2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="tab2" />
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
</TabHost>
</LinearLayout>

위 레이아웃에서 주목할 점은 FrameLayout이 TabWidget의 자식으로 선언되어 있다는 것입니다. 안드로이드 공식 문서에 따르면 탭 위젯의 콘텐츠 영역으로는 반드시 FrameLayout을 사용해야 하며, 각 탭의 실제 내용은 이 FrameLayout 안에 배치됩니다.

3단계: MainActivity 코드 작성

다음 코드를 src/MainActivity.java 파일에 추가합니다.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioButton;
import android.widget.TabHost;
public class MainActivity extends AppCompatActivity {
    RadioButton radioButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabHost tabs = (TabHost) findViewById(R.id.tabhost);
        tabs.setup();
        TabHost.TabSpec spec = tabs.newTabSpec("tag1");
        spec.setContent(R.id.tab1);
        spec.setIndicator("First");
        tabs.addTab(spec);
        spec = tabs.newTabSpec("tag2");
        spec.setContent(R.id.tab2);
        spec.setIndicator("second");
        tabs.addTab(spec);
    }
}

코드의 핵심 흐름은 다음과 같습니다. 먼저 findViewById()로 TabHost 객체를 가져온 후 setup() 메서드를 호출하여 초기화합니다. 그다음 newTabSpec()으로 각 탭의 스펙을 생성하고, setContent()로 탭에 표시할 콘텐츠를 지정한 뒤 setIndicator()로 탭 제목을 설정합니다. 마지막으로 addTab()을 호출하면 탭이 화면에 추가됩니다.

4단계: 매니페스트 파일 확인

이 예제는 별도의 권한이나 특수 설정이 필요하지 않으므로 manifest.xml 파일을 수정할 필요가 없습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 다음, 툴바의 실행(Run) 아이콘을 클릭하세요. 옵션 목록에서 연결된 모바일 기기를 선택하면 앱이 설치되고 실행됩니다.

앱이 정상적으로 실행되면 아래와 같이 첫 번째 탭이 기본 화면으로 표시됩니다.

안드로이드 TabHost 사용법, 단계별 예제로 쉽게 배우기

이제 두 번째 탭을 눌러 보세요. 아래 화면과 같이 두 번째 탭의 콘텐츠로 전환되는 것을 확인할 수 있습니다.

안드로이드 TabHost 사용법, 단계별 예제로 쉽게 배우기