一个activity 多个fragment写页面

2023-03-07  本文已影响0人  别看后面有人
1. FragmentTransaction区别add和replace
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()
        }
    }
上一篇下一篇

猜你喜欢

热点阅读