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>相对独立,不依赖外部。