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

Android Studio 프래그먼트(Fragment) 튜토리얼 – 예제 코드로 배우는 방법

Android Studio에서 프래그먼트(Fragment) 시작하기

프래그먼트(Fragment)는 하나의 액티비티 안에서 독립적인 UI 영역을 구성할 수 있는 재사용 가능한 컴포넌트입니다. 이 튜토리얼에서는 Android Studio에서 두 개의 버튼을 눌러 서로 다른 프래그먼트를 전환하는 간단한 예제를 단계별로 살펴보겠습니다.

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"
    tools:context = ".MainActivity"
    android:orientation = "vertical">
    <Button
       android:id = "@+id/fragment1"
       android:layout_width = "wrap_content"
       android:layout_height = "wrap_content"
       android:layout_alignParentTop = "true"
       android:layout_centerHorizontal = "true"
       android:layout_marginTop = "27dp"
       android:text = "fragment1"/>
    <Button
       android:id = "@+id/fragment2"
       android:layout_width = "wrap_content"
       android:layout_height = "wrap_content"
       android:layout_alignParentTop = "true"
       android:layout_centerHorizontal = "true"
       android:layout_marginTop = "27dp"
       android:text = "fragment2"/>
    <LinearLayout
       android:id = "@+id/layout"
       android:layout_width = "wrap_content"
       android:layout_height = "wrap_content"
       android:orientation = "vertical">
    </LinearLayout>
</LinearLayout>

위 코드에서는 서로 다른 프래그먼트를 화면에 표시하기 위해 두 개의 버튼(Button)과 프래그먼트가 들어갈 리니어 레이아웃(LinearLayout) 컨테이너를 사용했습니다.

3단계 – src/MainActivity.java 작성

메인 액티비티에서 버튼 클릭 이벤트를 처리하고, FragmentManager를 통해 프래그먼트를 교체(replace)합니다.

package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       final android.support.v4.app.Fragment first = new FirstFragment();
       final android.support.v4.app.Fragment second = new SecondFragment();
       findViewById(R.id.fragment1).setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
             android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
             android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
             fragmentTransaction.replace(R.id.layout, first);
             fragmentTransaction.commit();
          }
       });
       findViewById(R.id.fragment2).setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
             FragmentManager fm = getSupportFragmentManager();
             FragmentTransaction fragmentTransaction = fm.beginTransaction();
             fragmentTransaction.replace(R.id.layout, second);
             fragmentTransaction.commit();
          }
       });
    }
}

4단계 – src/FirstFragment.java 작성

첫 번째 프래그먼트 클래스입니다. onCreateView()에서 레이아웃을 inflate하고 TextView에 텍스트를 설정합니다.

package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class FirstFragment extends Fragment {
    TextView textView;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.fragment, container, false);
       textView = view.findViewById(R.id.text);
       textView.setText("first");
       return view;
    }
}

5단계 – src/SecondFragment.java 작성

두 번째 프래그먼트 클래스입니다. 첫 번째 프래그먼트와 동일한 구조이며, 표시되는 텍스트만 다릅니다.

package com.example.myapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class SecondFragment extends Fragment {
    TextView textView;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.fragment, container, false);
       textView = view.findViewById(R.id.text);
       textView.setText("Second");
       return view;
    }
}

6단계 – res/layout/fragment.xml 작성

두 프래그먼트가 공통으로 사용할 레이아웃 파일입니다. 중앙 정렬된 TextView 하나로 구성됩니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout
    xmlns:android = "https://schemas.android.com/apk/res/android"
    android:layout_width = "match_parent"
    android:gravity = "center"
    android:layout_height = "match_parent">
    <TextView
       android:id = "@+id/text"
       android:textSize = "30sp"
       android:layout_width = "match_parent"
       android:layout_height = "match_parent" />
</LinearLayout>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

Android Studio 프래그먼트(Fragment) 튜토리얼 – 예제 코드로 배우는 방법

화면의 버튼을 클릭하면 각각의 프래그먼트가 로드되며 아래와 같은 결과를 확인할 수 있습니다.

Android Studio 프래그먼트(Fragment) 튜토리얼 – 예제 코드로 배우는 방법


Android Studio 프래그먼트(Fragment) 튜토리얼 – 예제 코드로 배우는 방법