11-3 프래그먼트

StrayCat·2022년 11월 11일
0

프래그먼트

  • 플랫폼 API 에 android.app.Fragment가 있으나, 가능하면 androidx.fragment 를 사용하도록 한다.

프래그먼트 소개 - 액티비티처럼 동작하는 뷰

  • 프래그먼트는 액티비티화면을 구성하는 뷰이며 자체만으로는 화면에 아무것도 출력되지 않는다.

  • 액티비티처럼 동작하므로 액티비티에 작성할 수 있는 모든 코드는 프래그먼트에 사용할 수 있다.

  • 태블릿과 같은 넓은 화면에 여러 화면으로 분할하여 넣기위해서 개발되었다.(ex. 화면 왼쪽 목록에서 클릭하면 화면 오른쪽에 상세 내용이 뜸)

  • 하나의 액티비티에서 여러개의 프래그먼트를 작성하여 화면 전환을 할 수 있다.(ex. 뷰페이저, 탭 전환)

  • build.gradle 파일에 androidx.fragment를 추가하여 사용한다.

dependencies {
	...
    implementation 'androidx.fragment:fragment-ktx:1.5.4'
}
  • res/layout에 fragment_one.xml 레이아웃 파일 생성 후 아래와 같이 클래스를 생성한다.
class OneFragment : Fragment(){
    lateinit var binding: FragmentOneBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentOneBinding.inflate(inflater, container,false)
        return binding.root
    }
}
  • 위에서 생성된 Fragment 클래스를 액티비티 레이아웃 XML 파일에 추가한다.
<fragment
    android:name="com.example.doitkotlin3.OneFragment"
    android:id="@+id/fragmentView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Fragment 동적 추가

  • 만약 동적으로 프래그먼트를 생성하여 출력해야하는 경우에는 액티비티 레이아웃 XML 파일에 프래그먼트가 출력될 빈 뷰를 하나 생성해준다.
<androidx.appcompat.widget.LinearLayoutCompat
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragment_content"
    android:orientation="vertical">
    </androidx.appcompat.widget.LinearLayoutCompat>
  • FragmentManager를 통해 생성된 FragmentTransaction 클래스의 함수로 Fragment를 제어할 수 있다.
val fragmentManager : androidx.fragment.app.FragmentManager = supportFragmentManager
val transaction : androidx.fragment.app.FragmentTransaction = fragmentManager.beginTransaction()
val fragment = OneFragment()
transaction.add(R.id.fragment_content, fragment)
transaction.commit()

프래그먼트 생명주기

  • 프래그먼트는 액티비티처럼 동작하는 뷰이므로 생명주기 역시 액티비티와 같다.


(출처 - https://limkydev.tistory.com/41)

  • 액티비티 생명주기 참고용

    (출처 - https://latte-is-horse.tistory.com/274)

  • 프래그먼트의 생명주기는 크게 Initialized(초기화), Created(생성), Started(시작), Resumed(재개), Destroyed(소멸) 5단계로 구분된다.

  • 초기화단계에서는 onAttach(), onCreate() 가 호출되면서 프래그먼트 초기화 로직을 수행한다. 이때는 프래그먼트를 구성하는 뷰 객체를 이용하지 못한다.

  • 생성단계에서 onCreatedView() 가 호출되면서 LayoutInflater 객체가 넘어가므로 프래그먼트 내부를 구성하는 뷰 객체가 준비된다.

  • 백스택(back stack)

    • 프래그먼트가 화면에 보이지 않는 순간 제거하지 않고 저장했다가 다시 이용할 수 있는 기능이다.
    • onResume() 호출 이후 백스택(back stack)을 사용하는 경우, 뒤로가기 버튼이 눌렸을 때 onDestroyView() 까지만 호출되며 이전 프래그먼트로 화면을 전환할 수 있다. 다시 화면에 출력할 경우 OnCreateView() -> ... -> onResume() 까지 호출된다.
    • 백스택을 사용하지 않고 뒤로가기 버튼이 눌렸다면, onDestroy()까지 호출되어 제거된다.
    • FragmentTransaction 의 addToBackStack() 함수를 사용한다.
    transaction.addToBackStack(null)

0개의 댓글