이 포스팅은 아래 구글 코드랩을 개인 학습용으로 정리한 글입니다.
class TitleFragment : Fragment() {
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
}
}
<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>
Use the fragment tag to define the layout for the Fragment in the XML layout file.
Inflate the layout for a Fragment in onCreateView().
buildscript {
ext {
...
navigationVersion = '2.5.3'
}
...
}
dependencies{
...
implementation "androidx.navigation:navigation-fragment-ktx:$navigationVersion"
implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
...
}
res 폴더 우클릭>New>New Resource File
navigation.xml>Design>Navigation Editor
<fragment
android:id="@+id/myNavHostFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/navigation" />
➕ navigation.xml>Naviagation Editor>New Destination Button을 눌렀을 때 목록에 fragment_title이 나타나지 않는 현상 발생
해결 방법: 기존에 있던 TitleFragment.kt과 fragment_title.xml 삭제
-> Create New Destination > TitleFragment.kt과 fragment_title.xml 새로 생성
minSdkVersion 21 이상인 경우:
build.gradle(app) 파일에서 multiDexEnable을 true로 설정android { defaultConfig { ... multiDexEnabled true } ... }