1.官方文檔
https://developer.android.com/reference/kotlin/androidx/fragment/app/FragmentContainerView
在layout.xml中使用<fragment>封裝可復用控件時,lint時會報出警告,提示使用FragmentContainerView.
2.簡介
FragmentContainerView是一個 FrameLayout,可以指定大小、背景、可以findViewById等等。可以不用在相關的Fragment的layout中再次指定。
1 <androidx.fragment.app.FragmentContainerView 2 android:id="@+id/title_fgmt" 3 android:name="app.TitleFrgmt" 4 android:layout_width="0dp" 5 android:layout_height="0dp" 6 android:tag="可在fragment的arguments中取這個tag" 7 android:background="@color/colorWhite" 8 app:layout_constraintHeight_percent="0.08" 9 app:layout_constraintEnd_toEndOf="parent" 10 app:layout_constraintStart_toStartOf="parent" 11 app:layout_constraintTop_toTopOf="parent" />
2.1 其中兩個重要屬性
- android:tag : 指定fragment的Tag,可以在fragment中通過 getTag() 得到。
- android:name: 指定關聯的Fragment。
2.2 findviewById
1 binding.aboutTitleFrgmt.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener{ 2 override fun onPreDraw(): Boolean { 3 binding.aboutTitleFrgmt.findViewById<TextView>(R.id.title_txt)?.let { 4 it.setText("tttt") 5 } 6 binding.aboutTitleFrgmt.viewTreeObserver.removeOnPreDrawListener(this ) 7 return true 8 } 9 })
3.<fragment>與<inlcude >區別
- include只能簡單復用控件
- <fragment>可以復用復雜功能,如頁面里有list,控件的數據可能來自網絡等
- <fragment>相對獨立,不依賴外部。