静态加载
<fragment
android:id="@+id/fragment1"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:name="com.example.fragmentapplication.Fragment1"/>
动态加载
动态加载fragment
<FrameLayout
android:id="@+id/container"
android:layout_width="200dp"
android:layout_height="200dp">
val manager = supportFragmentManager
val transaction = manager.beginTransaction()
transaction.add(R.id.container, Fragment2())
transaction.commit()
动态修改fragment的内容
findViewById<View>(R.id.button).setOnClickListener {
val manager = supportFragmentManager
val f1 = manager.findFragmentById(R.id.fragment1)
val v1 = f1!!.view
val t1 = v1!!.findViewById<TextView>(R.id.txt1)
t1.text = "这是动态生成的内容"
}
在一个fragment中添加另一个fragment
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val v = inflater.inflate(R.layout.fragment_2, container, false)
v.findViewById<View>(R.id.txt2).setOnClickListener {
val transaction = fragmentManager!!.beginTransaction()
transaction.add(R.id.container, Fragment3())
transaction.commit()
}
return v
}