0

Can anyone help me to solve the problem when fragment reload data every single tab back.

This is my MainActivity

class MainActivity : AppCompatActivity() {


    private fun addBottomView(){
        bottomNav.setOnNavigationItemSelectedListener(object: BottomNavigationView.OnNavigationItemSelectedListener{

            override fun onNavigationItemSelected(p0: MenuItem): Boolean {
                var selectedItem: Fragment? = null
                when(p0.itemId){
                    R.id.words ->
                        selectedItem = FragmentA.newInstance()
                    R.id.writing ->
                        selectedItem = FragmentB.newInstance()
                    R.id.speaking ->
                        selectedItem = FragmentC.newInstance()
                    R.id.reading ->
                        selectedItem = FragmentD.newInstance()
                }
                var ft: FragmentTransaction = supportFragmentManager.beginTransaction()
                ft.replace(R.id.frame_layout, selectedItem!!)
                ft.commit()
                return true
            }
        })
        var ft: FragmentTransaction = supportFragmentManager.beginTransaction()
        ft.replace(R.id.frame_layout, WordsFragment.newInstance())
        ft.commit()

    }
}

I have found on the internet and youtube videos but no one answered this questions precisely, they recommended to use add, hide instead of replace but not so sure how to do it. if possible, can u guys explain it as clearly as you can :)

This is my ViewPageAdapter

class ViewPagerAdapter: FragmentPagerAdapter {

    private val mFragmentList: MutableList<Fragment> = mutableListOf()
    private val mFragmentTitleList : MutableList<String> = mutableListOf()

    constructor(manager: FragmentManager) : super(manager){

    }

    fun addFragment(fragment: Fragment, title: String){
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }

    override fun getItem(position: Int): Fragment {
        return mFragmentList.get(position)
    }

    override fun getCount(): Int {
        return mFragmentList.size
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitleList.get(position)
    }
}

Thanks

AskNilesh
  • 67,701
  • 16
  • 123
  • 163

1 Answers1

0

You can solve this by defining the fragments as singleton. for example:

class FragmentA: Fragment {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    companion object {

        private var instance: FragmentA? = null

        fun newInstance(): FragmentA {
            if (instance == null) instance = FragmentA()
            return instance!!
        }
    }
}
aminography
  • 21,986
  • 13
  • 70
  • 74