Fragment

심재·2024년 9월 11일
1

android

목록 보기
2/2

Fragment는 Android에서 UI 구성 요소를 재사용 가능하고 독립적으로 관리할 수 있는 작은 부분으로 분리할 수 있게 해주는 기능입니다. Fragment는 자체적인 생명 주기를 가지고 있으며, 하나의 Activity 내에서 여러 개의 Fragment를 추가, 제거, 교체할 수 있습니다. 이는 특히 복잡한 UI를 가진 앱에서 UI를 구성하고 관리하는 데 매우 유용합니다.

1. Fragment란?

정의: Fragment는 UI의 일부를 구성하는 모듈형 컴포넌트입니다. Activity 내에서 여러 개의 Fragment를 함께 사용할 수 있으며, 독립적으로 동작하고, 독자적인 UI와 로직을 가질 수 있습니다.

특징:
독립적인 생명 주기를 가짐.
재사용성이 높음.
UI와 비즈니스 로직을 분리하여 코드 유지보수를 쉽게 만듦.
동적 UI 변경에 유리.

2. Fragment의 생명 주기

Fragment는 Activity와 밀접하게 연동되며, 독립적인 생명 주기를 가집니다. 생명 주기 메서드는 다음과 같습니다:

onAttach(): Fragment가 Activity에 부착될 때 호출됩니다.
onCreate(): Fragment가 생성될 때 호출되며, 초기화 작업을 수행합니다.
onCreateView(): Fragment의 UI를 생성할 때 호출되며, 레이아웃을 설정합니다.
onViewCreated(): onCreateView가 끝난 후, 뷰와 관련된 초기화 작업을 수행합니다.
onStart(): Fragment가 사용자에게 보이기 시작할 때 호출됩니다.
onResume(): Fragment가 활성 상태가 되어 사용자와 상호작용할 수 있을 때 호출됩니다.
onPause(): Fragment가 일시 중지 상태가 될 때 호출됩니다.
onStop(): Fragment가 더 이상 사용자에게 보이지 않을 때 호출됩니다.
onDestroyView(): Fragment의 뷰가 파괴될 때 호출됩니다.
onDestroy(): Fragment가 완전히 소멸되기 전에 호출됩니다.
onDetach(): Fragment가 Activity에서 분리될 때 호출됩니다.

3. Fragment 구현 방법

1. Fragment 클래스 생성하기

먼저, Fragment 클래스를 생성하여 원하는 기능을 구현합니다.

// MyFragment.kt
class MyFragment : Fragment() {

    // onCreateView를 오버라이드하여 Fragment의 레이아웃을 설정
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Fragment의 레이아웃을 Inflate
        return inflater.inflate(R.layout.fragment_my, container, false)
    }
}

2. Fragment 레이아웃 파일 생성하기

Fragment가 사용할 레이아웃 파일을 생성합니다.

<!-- fragment_my.xml -->
<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:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, Fragment!"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

3. Activity에 Fragment 추가하기

XML로 추가: Activity의 레이아웃 파일에서 Fragment를 직접 선언할 수 있습니다.
xml

<!-- activity_main.xml -->
<androidx.fragment.app.FragmentContainerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container_view"
    android:name="com.example.MyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

코드로 추가: Activity에서 코드로 Fragment를 추가할 수 있습니다.

// MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Fragment 추가
        val fragment = MyFragment()
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container_view, fragment) // R.id.fragment_container_view는 Fragment가 들어갈 컨테이너의 ID
            .commit()
    }
}

4. Fragment의 동적 처리

Fragment 교체:
Fragment는 Activity 내에서 동적으로 교체할 수 있습니다. 이는 네비게이션이 필요하거나 UI가 상황에 따라 변해야 할 때 유용합니다.

// 다른 Fragment로 교체하는 코드
val newFragment = AnotherFragment()
supportFragmentManager.beginTransaction()
    .replace(R.id.fragment_container_view, newFragment)
    .addToBackStack(null) // 뒤로가기 버튼으로 이전 Fragment로 돌아갈 수 있도록 Back Stack에 추가
    .commit()

5. Fragment의 장점과 활용 사례

장점:

재사용성: 하나의 Fragment를 여러 Activity에서 재사용할 수 있어 코드 중복을 줄일 수 있습니다.
유연성: 화면 크기에 따라 Fragment 레이아웃을 변경할 수 있어, 태블릿과 스마트폰의 UI를 별도로 관리할 수 있습니다.
동적 UI: Activity에서 Fragment를 동적으로 추가하거나 제거할 수 있어, 앱의 구조를 유연하게 만들 수 있습니다.
활용 사례:

탭 구조: ViewPager와 함께 사용하여 탭 기반의 UI를 구성할 때 유용합니다.
네비게이션: Fragment를 사용하여 화면 전환과 네비게이션을 관리할 수 있습니다.
모듈화: 복잡한 UI를 여러 Fragment로 나누어 관리함으로써 코드의 가독성과 유지보수성을 높일 수 있습니다.

6. Fragment의 최신 트렌드: Navigation Component

Navigation Component는 Fragment를 사용하여 네비게이션을 관리할 수 있는 최신 Android Jetpack 라이브러리입니다.

장점:
코드로 작성하는 복잡한 네비게이션 로직을 XML로 시각화하여 쉽게 관리할 수 있습니다.
Safe Args를 사용하여 타입 안전한 인수 전달이 가능.
Fragment는 안드로이드 앱의 UI 구성에서 중요한 역할을 하며, 특히 복잡한 앱 구조에서 Fragment를 사용하면 UI를 효율적으로 관리하고, 유지보수성과 유연성을 크게 향상시킬 수 있습니다.

profile
언제나 개발중

0개의 댓글