1. FragmentTransaction区别add和replace
-
源码中关于add的解释
截屏2023-03-08 14.40.59.png -
源码中关于replace的解释
截屏2023-03-08 14.45.13.png
和明显,add是把fragment添加到容器中,replace是如果容器中有相同fragment的话,会先移除然后再添加,另外,如果使用add的话,需要配合hide一起使用,生命周期也会有很大不同当使用add的时候,onResume(),onPause(),onStop()这几个方法会走一次之前add进去的fragment,使用返回键的时候,onViewCreated()和onResume()也会执行之前add进去的fragment,而使用replace的时候,只会执行当前fragment的方法,不会执行之前fragment的生命周期
2.addToBackStack()这个方法是返回之前fragment的回退栈
下面是一个acitcity中添加多个fragment的代码:
class ThreeActivity : AppCompatActivity() {
private var TAG="TAG"
private lateinit var binding: ActivityThreeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityThreeBinding.inflate(layoutInflater)
setContentView(binding.root)
initView()
}
private fun initView(){
val fragmentOne=FragmentOne()
supportFragmentManager.beginTransaction().replace(R.id.lv_fragment_container,fragmentOne).commit()
binding.btBack.setOnClickListener {
onBackPressed()
}
}
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount<=0){
finish()
}else{
supportFragmentManager.popBackStack()
}
}
fragment 的代码
class FragmentOne:Fragment() {
private var TAG="TAG"
private lateinit var binding: FragmentThreeBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding=FragmentThreeBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tvTitle.text="FragmentOne"
binding.btNext.setOnClickListener {
val fragmentTwo=FragmentTwo()
val fragmentTransaction = parentFragmentManager.beginTransaction()
fragmentTransaction.addToBackStack(null)
fragmentTransaction.replace(R.id.lv_fragment_container,fragmentTwo)
fragmentTransaction.commit()
}
}
}
class FragmentTwo:Fragment() {
private var TAG="TAG"
private lateinit var binding: FragmentThreeBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding=FragmentThreeBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tvTitle.text="FragmentTwo"
binding.btNext.setOnClickListener {
val fragmentTwo=FragmentThree()
val fragmentTransaction = parentFragmentManager.beginTransaction()
fragmentTransaction.addToBackStack(null)
fragmentTransaction.replace(R.id.lv_fragment_container,fragmentTwo)
fragmentTransaction.commit()
}
}
网友评论