Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

yourginieus

Fragment : fragment 생성 및 layout에 fragment 추가 본문

Android/Android Kotlin 기초 실습 정리

Fragment : fragment 생성 및 layout에 fragment 추가

EOJIN 2022. 10. 25. 21:29

Fragment 

  • fragment는 Activity 안의 UI의 일부 또는 동작을 나타냄
  • 여러 fragment를 하나의 activity로 결합하여 multi-pane UI를 구축할 수 있음
  • 또한 많은 activity에 fragment를 재사용할 수 있음
- fragment는 자체 lifecycle이 있어 자체 input events를 받을 수 있음
- Activity가 실행되고 있는 동안 fragment를 추가 또는 삭제할 수 있음
fragment UI는 XML layout 파일에 정의 됨

STEP 1 : Fragment class 추가

  • 새로운 fragment를 위한 Kotlin class를 만드는 것부터 시작
  • File > New > Fragment > Fragment(Blank) 선택
  • Fragment 이름으로는 원하는 kt파일 이름 입력
  • Fragment layout 이름에 원하는 레이아웃 xml 파일 이름 입력
  • 그리고 finisn -> 프래그먼트 kt 파일과 xml 파일이 생성됨!
    • .kt 파일에는 onCreateView() method가 이미 있을 것 : Fragment's lifecycle 중 호출되는 메소드 중 하나
    • onCreateView() 내부의 다른 코드들은 전부 지우기
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                         savedInstanceState: Bundle?): View? {
}
  • 프래그먼트를 사용하려면 바인딩 오브젝트를 만들어야 함
    • 바인딩 오브젝트를 만들고 프래그먼트의 view를 확장해야 함! Activity의 setContentView처럼!
    • onCreateView 안에서 binding 변수를 만든 후, DataBindingUtil,inflate() 호출, 4개 인수 전달
      • inflater : LayoutInflater -> binding layout을 확장하는 데 사용
      • XML layout resource : 확장할 레이아웃의 리소스
      • container : 부모의 viewgroup
      • false : attachToParent에 대한 값
    • 이 DataBindingUtil.inflate 의 리턴값을 binding 변수에 할당함
    • onCreateView method의 return 값으로 binding.root 반환
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                         savedInstanceState: Bundle?): View? {
   val binding = DataBindingUtil.inflate<FragmentTitleBinding>(inflater,
           R.layout.fragment_title,container,false)
   return binding.root
}

STEP 2 : Main 레이아웃 파일에 새로운 fragment 추가

  • 레이아웃 xml 파일에 fragment 추가하기
  • <LinearLayout> 태그 안에 <fragment> 태그 추가
  • fragment의 id를 알맞게 설정하고
  • fragment의 name을 fragment class의 전체 경로로 설정
  • 레이아웃의 width와 height를 match_parent로 설정
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <fragment
                android:id="@+id/titleFragment"
                android:name="com.example.android.navigation.TitleFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />
        </LinearLayout>

</layout>

 

 

https://developer.android.com/codelabs/kotlin-android-training-create-and-add-fragment?index=..%2F..android-kotlin-fundamentals&hl=ko#0 

 

Comments