从底部导航按回时如何避免片段重新加载数据

时间:2018-08-31 09:30:24

标签: android android-fragments kotlin bottomnavigationview

fragment每隔一个选项卡重新加载数据时,谁能帮助我解决问题。

这是我的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()

    }
}

我已经在互联网和youtube视频上找到了,但是没有人精确地回答这个问题,他们建议使用添加隐藏而不是替换但不确定如何做。如果可能的话,你们能解释得越清楚越好:)

这是我的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)
    }
}

谢谢

1 个答案:

答案 0 :(得分:0)

您可以通过将片段定义为单例来解决此问题。例如:

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!!
        }
    }
}