iT邦幫忙

0

【Android studio】【kotlin】 使用BottomNavigationView切換fragment不銷毀fragment

我想利用BottomNavigationView進行fragment之間的切換,但使用官方範例文件的作法會使原來的fragment被replace,我希望在切換fragment後原fragment還能保持在切換前的狀態,我上網找了一些資料,使用fragment transaction來進行切換,但是失敗了,fragment沒有切換,有甚麼方法可以解決嗎?

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar : androidx.appcompat.widget.Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        val manager = supportFragmentManager
        val transaction = manager.beginTransaction()
        transaction.replace(R.id.frameLayout, FragmentAdd()).commit()




        val navView: BottomNavigationView = findViewById(R.id.bottomNav)
        navView.setOnNavigationItemSelectedListener(listener)


    }

    private var listener = object :BottomNavigationView.OnNavigationItemSelectedListener {
        override fun onNavigationItemSelected(item: MenuItem): Boolean {
            val manager = supportFragmentManager
            val transaction = manager.beginTransaction()
            when (item.itemId) {
                R.id.item_add -> {
                    if (FragmentAdd ==null){
                        transaction.add(R.id.frameLayout, FragmentAdd)
                    }else{
                        transaction.show(FragmentAdd())
                    }
                    if(FragmentCard != null){
                        transaction.hide(FragmentCard())
                    }
                    transaction.commit()
                    return true
                }
                R.id.item_card -> {
                    if (FragmentCard==null){
                        transaction.add(R.id.frameLayout, FragmentCard)
                    }else{

                        transaction.show(FragmentCard())
                    }
                    if (FragmentAdd != null){
                        transaction.hide(FragmentAdd())
                    }
                    transaction.commit()
                    return true
                }
                else -> return true
            }

        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (currentFocus != null) {
            val imm: InputMethodManager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            android.R.id.home ->{
                onBackPressed()
                return true
            }
            else -> return super.onOptionsItemSelected(item)
        }
    }
}
可以 google 'bottomnavigationview fragment keep' 看看,蠻多人有同樣的問題

尚未有邦友回答

立即登入回答