add fragment防止fragment重建,show和hide的使用

(1)布局




    

        

            

            

            

            

            

        

    

    

    

    


(2)MainActivity中切换

class MainActivity : BaseActivity() {

    private lateinit var fTransition: FragmentTransaction

    var currentFragment = Fragment()

    override fun initData() {
    }

    override fun initView() {
        val mNewsFragment = NewsFragment()
        val mVideoFragment = VideoFragment()
        val mCommunityFragment = CommunityFragment()
        val mUserFragment = UserFragment()

        mainRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            var mFragment: Fragment? = null
            when(checkedId){
                R.id.mainNews -> {
                    mFragment = mNewsFragment
                }
                R.id.mainVideo -> {
                    mFragment = mVideoFragment
                }
                R.id.mainCommunity -> {
                    mFragment = mCommunityFragment
                }
                R.id.mainUser -> {
                    mFragment = mUserFragment
                }
            }
            if (mFragment != null) {
                switchFragment(mFragment)
            }
        }
        mainRadioGroup.check(R.id.mainNews)
    }

    private fun switchFragment(fragment: Fragment){
        fTransition = supportFragmentManager.beginTransaction()
        if (currentFragment != fragment){
            fTransition.hide(currentFragment)
            currentFragment = fragment
            if (!fragment.isAdded){
                fTransition.add(R.id.mainFrame,fragment).show(fragment).commit()
            }else{
                fTransition.show(fragment).commit()
            }
        }
    }

    override fun getLayoutId() = R.layout.activity_main

    override fun setupPresenter(): MainPresenter? = MainPresenter(applicationContext)

你可能感兴趣的:(add fragment防止fragment重建,show和hide的使用)